【问题标题】:MVC3 How To Bind Multiple Checkboxes to 1 Property in ViewModelMVC3 如何将多个复选框绑定到 ViewModel 中的 1 个属性
【发布时间】:2011-12-20 16:21:02
【问题描述】:

我需要显示一个复选框列表,可以选中多个。

当用户点击提交时,这些复选框的值需要进入 ViewModel 中的一个属性...这是我目前得到的...

public class RegisterModel
{
    public List<string> Roles { get; set; }
    public List<RoleModel> SelectedRoles { get; set; }    
}
public class RoleModel
{
    public string RoleName { get; set; }
}

在我看来我正在尝试这样做......

@foreach (var role in Model.Roles)
{
    @Html.CheckBoxFor(m => m.SelectedRoles, role.RoleName)@role.RoleName
}

我收到以下错误:

CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'bool'

谁能告诉我我做错了什么?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 checkbox viewmodel model-binding


    【解决方案1】:

    简单:调整您的视图模型以匹配您的视图要求(即显示某些角色的复选框列表),使用编辑器模板并避免在视图中编写循环。

    所以:

    查看模型:

    public class RegisterModel
    {
        public List<RoleModel> Roles { get; set; }
    }
    
    public class RoleModel
    {
        public string RoleName { get; set; }
        public bool Selected { get; set; }
    }
    

    控制器:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new RegisterModel
            {
                Roles = new[]
                {
                    new RoleModel { RoleName = "administrator" },
                    new RoleModel { RoleName = "developer" },
                    new RoleModel { RoleName = "janitor :-)" },
                }.ToList()
            };
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Index(RegisterModel model)
        {
            // at this stage the model will contain all the 
            // information you need
            return View(model);
        }
    }
    

    查看(~/Views/Home/Index.cshtml):

    @model RegisterModel
    
    @using (Html.BeginForm())
    {
        @Html.EditorFor(x => x.Roles)
        <button type="submit">OK</button>
    }
    

    编辑器模板(~/Views/Home/EditorTemplates/RoleModel.cshtml):

    @model RoleModel
    
    <div>
        @Html.HiddenFor(x => x.RoleName)
        @Html.CheckBoxFor(x => x.Selected)
        @Html.LabelFor(x => x.Selected, Model.RoleName)
    </div>
    

    【讨论】:

    • 感谢您的快速回复!
    • 干得好!不知道 EditorFor 会这么好地处理列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多