Asp.Net MVC4显示CheckboxList

我搜索了很多,只花了3天时间搜索和尝试不同的技术(在stackoverflow等),但我找不到在asp.net mvc中实现checkboxlist的解决方案。 最后我将我的问题发布到stackoverflow;
所以,我的模型看起来像这样;

我的模型的多对多关系(1个类别可能包含许多项目,而一个项目可能属于许多类别)rel

我的模型的多对多关系(1个类别可能包含许多项目,项目可能属于许多类别)
我的控制器;

[HttpGet] [Authorize(Roles = "Admin")] public ActionResult ProjectAdd() { return View(); } 

我的看法;

 @using (Html.BeginForm()) { @Html.ValidationSummary(true) 
Add New Project
@Html.LabelFor(model => model.ProjectHeading)
@Html.EditorFor(model => model.ProjectHeading) @Html.ValidationMessageFor(model => model.ProjectHeading)
@Html.LabelFor(model => model.ProjecctUrl)
@Html.EditorFor(model => model.ProjecctUrl) @Html.ValidationMessageFor(model => model.ProjecctUrl)
@Html.LabelFor(model => model.ProjectLongDescription)
@Html.EditorFor(model => model.ProjectLongDescription) @Html.ValidationMessageFor(model => model.ProjectLongDescription)
@Html.LabelFor(model => model.PromoFront)
@Html.EditorFor(model => model.PromoFront) @Html.ValidationMessageFor(model => model.PromoFront)
@Html.LabelFor(model => model.ProjectThubmnail)
@Html.EditorFor(model => model.ProjectThubmnail) @Html.ValidationMessageFor(model => model.ProjectThubmnail)
@Html.LabelFor(model => model.ProjectImage)
@Html.EditorFor(model => model.ProjectImage) @Html.ValidationMessageFor(model => model.ProjectImage)
@Html.LabelFor(model => model.CategoryId)
@Html.EditorFor(model => model.CategoryId) @Html.ValidationMessageFor(model => model.CategoryId)

所以,我的问题是如何在视图中显示类别的复选框列表?
如何从该复选框列表中获取选定的值?

您需要一个具有所有类别列表的对象,例如,您可以这样做:

 [HttpGet] [Authorize(Roles = "Admin")] public ActionResult ProjectAdd() { // Get all categories and pass it into the View ViewBag.Categories = db.ListAllCategories(); return View(); } 

在视图的顶部

 @model Database.Project @{ // retrieve the list of Categories List categories = ViewBag.Categories; } 

然后替换它

  
@Html.LabelFor(model => model.CategoryId)
@Html.EditorFor(model => model.CategoryId) @Html.ValidationMessageFor(model => model.CategoryId)

为了这

  
@foreach(var c in categories) { }

回到你的控制器

 [HttpPost] [Authorize(Roles = "Admin")] public ActionResult ProjectAdd(Database.Project model, int[] categories) { if(ModelState.IsValid) { // fill up categories db.InsertAndSaveProject(model, categories); } ... return redirectToView("ProjectAdd"); } 

@balexandre上面提出的答案很有用。 但是,我在CheckBoxList中使用了以下HTML扩展。

1. ASP.net MVC4中的CheckboxList
2.源代码:HTML扩展助手方法(Github)

使用此辅助方法的主要优点是代码清晰,可读性更高。 例如

 @Html.CheckBoxListFor(model => model.SelectedItems, Model.AllItems)