<Object> HttpPost 中的列表为空



我的 MVC5 Web 应用程序中有一个管理页面,其中选择了用户,单击继续按钮后,将显示带有复选框的所有角色的列表(通过 Ajax(。如果用户具有这些角色中的任何一个,则将自动选中该复选框。

我想在用户选中/取消选中每个角色的框后在我的 HttpPost 方法中传递一个列表。但是,我的操作方法的参数为空,但 Request.Form 中有值。

我不明白为什么会这样。另外,我真的需要为视图模型中的每个参数使用@Html.HiddenFor()才能正常工作吗?

角色复选框视图模型

public class RoleCheckBoxViewModel
{
    [Display(Name = "Choose Role(s)")]
    [Key]
    public string RoleId { get; set; }
    public string UserId { get; set; }
    public string Name { get; set; }
    [Display(Name="boxes")]
    public bool IsChecked { get; set; }
}

角色控制器操作

[HttpPost]
public ActionResult Update(List<RoleCheckBoxViewModel> list) //the model in my view is a List<RoleCheckBoxViewModel> so then why is it null?
{
      //these next two lines are so that I can get to the AddToRole UserManagerExtension 
      var userStore = new UserStore<ApplicationUser>(_context);
        var userManager = new UserManager<ApplicationUser>(userStore);
        foreach (var item in Request.Form) //it's messy but I can see the data in this Form
        {
            System.Console.WriteLine(item.ToString());
        }
        //AddToRole for any new checkboxes checked
        //RemoveFromRole any new checkboxes unchecked
        //context save changes
        return RedirectToAction("Index");
}

AllRoles 分部视图(先前 AJAX 调用的结果(

@model List<Core.ViewModels.RoleCheckBoxViewModel>

@using (Html.BeginForm("Update", "Roles", FormMethod.Post))
{
<p>
    Select Roles
</p>
<table class="table">
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(model => item.Name)
                @Html.CheckBoxFor(model => item.IsChecked)
            </td>
        </tr>
        @Html.HiddenFor(model => item.RoleId)
        @Html.HiddenFor(model => item.UserId)
        @Html.HiddenFor(model => item.IsChecked)
        @Html.HiddenFor(model => item.Name)
    }
</table>
<input type="submit" value="Save" class="glyphicon glyphicon-floppy-save" />
}

集合中的模型绑定器需要对输入控件的名称编制索引,以作为集合在控制器操作中发布。 您可以将循环更改为使用 for 循环,并在帮助程序方法中执行索引,是的,如果您不希望用户编辑要发布的属性,则需要为要发布的属性创建隐藏输入。

您可以将循环代码更改为如下所示,以使模型正确回发:

@for(int i=0; i < Model.Count' i++)
{
    <tr>
        <td>
            @Html.DisplayFor(model => Model[i].Name)
            @Html.CheckBoxFor(model => Model[i].IsChecked)
        </td>
    </tr>
        @Html.HiddenFor(model => Model[i].RoleId)
        @Html.HiddenFor(model => Model[i].UserId)
        @Html.HiddenFor(model => Model[i].IsChecked)
        @Html.HiddenFor(model => Model[i].Name)
}

希望对您有所帮助!

最新更新