我有一个显示用户列表的 View ,将模型设置为:
@model List<MyProject.Models.User>
在此 View 中,我希望能够选择对特定用户执行操作,即向 Controller 发送我想禁用用户的信息。如何将特定的用户对象发布到 Controller ?
这是我到目前为止所得到的,但我看不到如何从集合中发布特定对象:
@foreach (var c in Model)
{
<tr>
<td>@c.Username</td>
<td>@c.IsEnabled</td>
<td>
@using (Html.BeginForm("DisableUser", "UserManagement"))
{
<input type="submit" value="Disable" class="btn btn-primary"/>
}
</td>
</tr>
}
我的 Controller 有签名:
public ActionResult DisableUser(User user)
最佳答案
无需回发 User
的所有属性,您只需在 BeginForm()
方法中添加路由值即可回发 ID 或 User .假设该属性名为
UserId`,则
@foreach (var c in Model)
{
<tr>
....
<td>
@using (Html.BeginForm("DisableUser", "UserManagement", new { id = c.UserId ))
{
<input type="submit" value="Disable" class="btn btn-primary"/>
}
</td>
</tr>
}
Controller 方法是
public ActionResult DisableUser(int id)
{
// Get the User based on id, update it and redirect
}
您还可以考虑使用 ajax 提交值,这将允许用户停留在同一页面上并继续“禁用”其他 User
对象,而无需进行重定向,其中如果代码可能是
@foreach (var c in Model)
{
<tr>
....
<td>
<button type="button" class="disable" data-id="@c.UserId">Disable</button>
</td>
</tr>
}
var url = '@Url.Action("DisableUser", "UserManagement")';
$('.disable').click(function() {
var row = $(this).closest('tr');
$.post(url, { id: $(this).data('id') }, function(result) {
if(result) {
// for example, remove the row from the table
row.remove();
} else {
// Oops
}
}).fail(function (result) {
// Oops
});
});
Controller 方法是
public JsonResult DisableUser(int id)
{
// Get the User based on id and update it
return Json(true);
// or if the update failed - return Json(null);
}
关于c# - 将模型集合中的一项发布到 MVC 中的 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37481664/