asp.net-mvc - MVC3 如何将多个复选框绑定(bind)到 ViewModel 中的 1 个属性

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

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

当用户点击提交时,这些复选框的值需要进入 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'

有人可以告诉我我做错了什么吗?

最佳答案

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

所以:

查看模型:

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

public class RoleModel
{
    public string RoleName { get; set; }
    public bool Selected { get; set; }
}

Controller :

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

View (~/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>

关于asp.net-mvc - MVC3 如何将多个复选框绑定(bind)到 ViewModel 中的 1 个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7986991/

相关文章:

asp.net - ASP MVC - 有问题的路线?

asp.net-mvc-3 - 使用新的代码安全模型保护网站程序集

mvvm - 在 ZK 框架中使用 MVVM 的奇怪复选框行为

php - 如何遍历数组以插入数据库

c# - 将 dataGridView 列转换为复选框列

c# - HtmlHelper 将 & 编码为 &

c# - ASP.Net MVC - String.Join()

c# - 如何将数据库表列映射到 Dapper .Net 中的类属性

javascript - ASP Net MVC 从 JS 错误调用 Controller 中的函数

c# - Office Open XML SDK 电子表格如何在数字前显示货币符号?