MVC3如何在视图模型绑定多个复选框房产 [英] MVC3 How To Bind Multiple Checkboxes to 1 Property in ViewModel
问题描述
我需要显示复选框列表,其中多于一个可以被检查。
I need to display a list of checkboxes, which more than one can be checked.
当用户点击提交,这些复选框的值需要进入的视图模型的属性......这是我走到这一步......
When the user hits submit, the value of these checkboxes need to go into a property in the ViewModel...this is what I got so far...
public class RegisterModel
{
public List<string> Roles { get; set; }
public List<RoleModel> SelectedRoles { get; set; }
}
public class RoleModel
{
public string RoleName { get; set; }
}
在视图中我试图做到这一点...
In the view I am trying to do this...
@foreach (var role in Model.Roles)
{
@Html.CheckBoxFor(m => m.SelectedRoles, role.RoleName)@role.RoleName
}
我收到以下错误:
I get the following error:
CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'bool'
谁能告诉我什么,我做错了吗?
Can someone tell me what I'm doing wrong?
推荐答案
简单:适应您的视图模式,以满足你的意见的要求(这是显示一个复选框列表一些角色),使用的编辑器模板和避免写循环您的看法。
Simple: adapt your view models to match your views requirement (which is to show a list of checkboxes for some roles), use editor templates and avoid writing loops in your views.
所以:
查看模式:
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);
}
}
查看(〜/查看/主页/ Index.cshtml
)
@model RegisterModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Roles)
<button type="submit">OK</button>
}
编辑模板(〜/查看/主页/ EditorTemplates / RoleModel.cshtml
)
@model RoleModel
<div>
@Html.HiddenFor(x => x.RoleName)
@Html.CheckBoxFor(x => x.Selected)
@Html.LabelFor(x => x.Selected, Model.RoleName)
</div>
这篇关于MVC3如何在视图模型绑定多个复选框房产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!