c# - 将模型集合中的一项发布到 MVC 中的 Controller 方法

标签 c# asp.net-mvc

我有一个显示用户列表的 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/

相关文章:

asp.net - ASP.NET MVC 中的分页

c# - async static Task<T> someMethod() 与 static async Task<T> someOtherMethod() 之间有什么区别

c# - 为什么 C# 编译器不认为这种泛型类型推断有歧义?

c# - 如何将 String 拆分为 2 种不同的类型?

javascript - 使用 javascript instant.js 库处理图像不适用于 ajax

asp.net-mvc - 我如何安排将我的图标缓存在 MVC3 中?

c# - 如何确定一个字符串是否包含来自另一个字符串的单词

c# - Excel 互操作在装有 Office 2007 的机器上工作,但在装有 Office 2010 的机器上失败

c# - 将查询字符串值绑定(bind)到字典

asp.net-mvc - 使用 AuthorizeAttribute 时最初设置 ReturnUrl 参数的内容