如何修改创建方法?
How to modify create method?
我有这个型号:
public class UsuarioMusica
{
public int UsuarioMusicaId { get; set; }
public int UserId { get; set; }
public int MusicId {get; set;}
}
我生成了一个控制器和视图,但我将只讨论创建方法。
我的问题是,我需要从登录用户那里获取UserId 和"MusicId" 在table 处建立关系,对吗?所以,我在音乐控制器中创建了一个搜索视图和搜索方法,列出了保存在音乐模型中的所有音乐,搜索视图:
@model IEnumerable<TestTcc2.Models.Musica>
@{
ViewBag.Title = "Search";
Layout = "~/Views/Shared/_LayoutOuvinte.cshtml";
}
<h2>Busca de Música</h2>
<table class="table table-hover table-bordered">
<tr>
<th>
<span>Genero</span>
</th>
<th>
<span>Nome</span>
</th>
<th>
<span>Artista</span>
</th>
<th>
<span>Preço</span>
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.genero.Nome)
</td>
<td>
@Html.DisplayFor(modelItem => item.Nome)
</td>
<td>
@Html.DisplayFor(modelItem => item.NomeArtista)
</td>
<td>
@Html.DisplayFor(modelItem => item.Preco)
</td>
<td>
@Html.ActionLink("Play", "", new { path = item.path }) |
</td>
</tr>
}
</table>
我的想法是,在这个视图中,我将为每一行创建一个新的 link,例如 @Html.ActionLink("Add music to my collection", "Create", "UsuarioMusica" })
,它将调用 create 方法和将向 usuarioMusica 模型添加登录用户的 userId 和 table.
中列出的音乐的 musicId
但我不知道如何在 UsuarioMusica 控制器的创建方法上执行此操作,实际上,这是我的创建方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(UsuarioMusica usuariomusica)
{
if (ModelState.IsValid)
{
db.UsuarioMusicas.Add(usuariomusica);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(usuariomusica);
}
这里的主要困难是如何修改创建方法以从用户在 link "Add music to my collection" 上创建并保存在 UsuarioMusica 的行中的音乐中获取 userID、musicID table.
@Html.ActionLink
是重定向到 GET 方法。您需要为 post 项目 ID 的每一行包含一个 <form>
元素。但是,这意味着每次 post 时都需要重新创建视图,因此使用 ajax.
将大大提高性能
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(m => item.genero.Nome)
</td>
......
<td>
<button type="button" class="addmusic" data-id="@item.MusicaId">Add</button>
</td>
}
请注意,项目 ID 已添加到按钮数据属性中,因此可以在脚本中检索它
脚本
var url = '@Url.Action("Create", "YourControllerName")'; // adjust to suit
$('.addmusic').click(function() {
var self = $(this);
// Get the ID
var id = self.data('id');
// post the value
$.post(url, { musicaID: id }, function(data) {
if(data) {
// remove the button so the item cannot be added more than once
self.remove();
} else {
// Oops, something went wrong - display message?
}
});
});
注意:要从 DOM(不仅仅是按钮)中删除项目行,请使用
if(data) {
var row = self.closest('tr')
row.remove();
}
和控制器
[HttpPost]
public JsonResult Create(int musicaID)
{
var userID = // you should know this on the server
// call a service that saves the userID and musicaID to the database
var usuariomusica = new UsuarioMusica()
{
UserId = userID,
MusicId = musicaID
};
db.UsuarioMusicas.Add(usuariomusica);
db.SaveChanges();
return Json(true);
}
注意:如果保存方法失败,则使用 return Json(null)
以便通知脚本失败。还要注意 [ValidateAntiForgeryToken]
的缺失。如果你想要这个,那么令牌也需要在ajax请求中传递如下
var token = $('input[name="__RequestVerificationToken"]').val();
$.post(url, { musicaID: id, __RequestVerificationToken: token }, function(data) {
我有这个型号:
public class UsuarioMusica
{
public int UsuarioMusicaId { get; set; }
public int UserId { get; set; }
public int MusicId {get; set;}
}
我生成了一个控制器和视图,但我将只讨论创建方法。 我的问题是,我需要从登录用户那里获取UserId 和"MusicId" 在table 处建立关系,对吗?所以,我在音乐控制器中创建了一个搜索视图和搜索方法,列出了保存在音乐模型中的所有音乐,搜索视图:
@model IEnumerable<TestTcc2.Models.Musica>
@{
ViewBag.Title = "Search";
Layout = "~/Views/Shared/_LayoutOuvinte.cshtml";
}
<h2>Busca de Música</h2>
<table class="table table-hover table-bordered">
<tr>
<th>
<span>Genero</span>
</th>
<th>
<span>Nome</span>
</th>
<th>
<span>Artista</span>
</th>
<th>
<span>Preço</span>
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.genero.Nome)
</td>
<td>
@Html.DisplayFor(modelItem => item.Nome)
</td>
<td>
@Html.DisplayFor(modelItem => item.NomeArtista)
</td>
<td>
@Html.DisplayFor(modelItem => item.Preco)
</td>
<td>
@Html.ActionLink("Play", "", new { path = item.path }) |
</td>
</tr>
}
</table>
我的想法是,在这个视图中,我将为每一行创建一个新的 link,例如 @Html.ActionLink("Add music to my collection", "Create", "UsuarioMusica" })
,它将调用 create 方法和将向 usuarioMusica 模型添加登录用户的 userId 和 table.
但我不知道如何在 UsuarioMusica 控制器的创建方法上执行此操作,实际上,这是我的创建方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(UsuarioMusica usuariomusica)
{
if (ModelState.IsValid)
{
db.UsuarioMusicas.Add(usuariomusica);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(usuariomusica);
}
这里的主要困难是如何修改创建方法以从用户在 link "Add music to my collection" 上创建并保存在 UsuarioMusica 的行中的音乐中获取 userID、musicID table.
@Html.ActionLink
是重定向到 GET 方法。您需要为 post 项目 ID 的每一行包含一个 <form>
元素。但是,这意味着每次 post 时都需要重新创建视图,因此使用 ajax.
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(m => item.genero.Nome)
</td>
......
<td>
<button type="button" class="addmusic" data-id="@item.MusicaId">Add</button>
</td>
}
请注意,项目 ID 已添加到按钮数据属性中,因此可以在脚本中检索它
脚本
var url = '@Url.Action("Create", "YourControllerName")'; // adjust to suit
$('.addmusic').click(function() {
var self = $(this);
// Get the ID
var id = self.data('id');
// post the value
$.post(url, { musicaID: id }, function(data) {
if(data) {
// remove the button so the item cannot be added more than once
self.remove();
} else {
// Oops, something went wrong - display message?
}
});
});
注意:要从 DOM(不仅仅是按钮)中删除项目行,请使用
if(data) {
var row = self.closest('tr')
row.remove();
}
和控制器
[HttpPost]
public JsonResult Create(int musicaID)
{
var userID = // you should know this on the server
// call a service that saves the userID and musicaID to the database
var usuariomusica = new UsuarioMusica()
{
UserId = userID,
MusicId = musicaID
};
db.UsuarioMusicas.Add(usuariomusica);
db.SaveChanges();
return Json(true);
}
注意:如果保存方法失败,则使用 return Json(null)
以便通知脚本失败。还要注意 [ValidateAntiForgeryToken]
的缺失。如果你想要这个,那么令牌也需要在ajax请求中传递如下
var token = $('input[name="__RequestVerificationToken"]').val();
$.post(url, { musicaID: id, __RequestVerificationToken: token }, function(data) {