问题
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?
回答1:
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.
So:
View model:
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>
}
Editor template (~/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>
来源:https://stackoverflow.com/questions/7986991/mvc3-how-to-bind-multiple-checkboxes-to-1-property-in-viewmodel