【问题标题】:How do I bind to a List as a Property on a Model in MVC 3 Razor?如何绑定到列表作为 MVC 3 Razor 中模型上的属性?
【发布时间】:2012-04-02 04:50:12
【问题描述】:

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

public class EditUserViewModel
    {
        public EditUserViewModel()
        {

        }
        public EditUserDataModel User { get; set; }
    }

使用如下所示的支持对象:

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; }
}

UserRoleListDataModel 看起来像这样:

public class UserRoleListDataModel
{
    public Guid Id { get; set; }
    public string RoleName { get; set; }
    public bool UserIsInRole { get; set; }
}

然后,在我的 Razor 文件中,我使用的是这样的整个东西:

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

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

控制器上的提交操作如下所示:

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

有人有什么建议吗?

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-3 razor checkboxfor


【解决方案1】:

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>
}

【讨论】:

  • +1 为索引属性正确使用 Razor 语法。虽然 Chris 值得(并获得)功劳,但您的答案是正确的,应该这样标记。
  • 谢谢你,我在 2018 年在这里使用 Razor Pages,总是忘记如何绑定列表!
【解决方案2】:

在你的剃须刀上试试这个:

@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>
}

这有点手动,但应该可以完成这项工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 2017-05-13
    • 2015-05-18
    • 2022-01-25
    相关资源
    最近更新 更多