如何在MVC 3 Razor中将模型作为属性绑定到List?

Joe*_*Joe 5 asp.net-mvc checkboxfor razor asp.net-mvc-3

我有一个看起来像这样的模型:

public class EditUserViewModel
    {
        public EditUserViewModel()
        {

        }
        public EditUserDataModel User { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

使用如下所示的后备对象:

public class EditUserDataModel
{
    public EditUserDataModel()
    {
        Roles = new List<UserRoleListDataModel>();
    }
    [DisplayName("First Name")]
    public string FirstName { get; set; }
    [DisplayName("Last Name")]
    public string LastName { get; set; }
    [DisplayName("Full Name")]
    public string FullName { get { return FirstName + " " + LastName; } }
    public List<UserRoleListDataModel> Roles { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

UserRoleListDataModel看起来像这样:

public class UserRoleListDataModel
{
    public Guid Id { get; set; }
    public string RoleName { get; set; }
    public bool UserIsInRole { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后,在我的Razor文件中,我正在使用整个事情:

@foreach (var role in Model.User.Roles)
{
<tr>
    <td>@role.RoleName</td>
    <td>@Html.CheckBoxFor(x=>role.UserIsInRole)</td>
</tr>
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,当我提交表单并点击我的控制器操作时,我的新模型上没有填充角色列表.

以下是控制器上的提交操作:

public ActionResult EditUser(EditUserViewModel model) // model.User.Roles is empty.
{
    // Do some stuff...
    return RedirectToAction("UserList");
}
Run Code Online (Sandbox Code Playgroud)

有人有什么建议吗?

Joe*_*Joe 10

Cris Carew很接近,让我走上正轨.

@for (int i=0;i < Model.User.Roles.Count;i++)
{
    @Html.Hidden("User.Roles.Index", i)
    @Html.HiddenFor(x => x.User.Roles[i].RoleName)
    <tr>
        <td>@Html.DisplayFor(x => Model.User.Roles[i].RoleName)</td>
        <td>@Html.CheckBoxFor(x => Model.User.Roles[i].UserIsInRole)</td>
    </tr>
}
Run Code Online (Sandbox Code Playgroud)

  • 正确使用索引属性的Razor语法的+1.虽然克里斯应得(并获得)信用,但你的是正确的答案,应该标记为这样. (2认同)

Chr*_*rew 6

在你的剃须刀中尝试这个:

@for (int i=0;i < Model.User.Roles.Count;i++)
{
@Html.Hidden("User.Roles.Index",i);
<tr>
    <td>@role.RoleName</td>
    <td>@Html.CheckBox("User.Roles[" + i + "].UserIsInRole",role.UserIsInRole)</td>
</tr>
}
Run Code Online (Sandbox Code Playgroud)

这有点手动,但应该做的工作.