I have searched a lot and spend 3 days only for searching and trying different technique (on stackoverflow etc) but I find no solution for implementing checkboxlist in asp.n
You need to have an object that will have a list of all categories, for example, you could do this:
[HttpGet]
[Authorize(Roles = "Admin")]
public ActionResult ProjectAdd()
{
// Get all categories and pass it into the View
ViewBag.Categories = db.ListAllCategories();
return View();
}
in the top of your View
@model Database.Project
@{
// retrieve the list of Categories
List<Database.Category> categories = ViewBag.Categories;
}
and then replace this
<div class="editor-label">
@Html.LabelFor(model => model.CategoryId)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CategoryId)
@Html.ValidationMessageFor(model => model.CategoryId)
</div>
for this
<div class="editor-label">
<label for="categories">Categories</label>
</div>
<div class="editor-field">
@foreach(var c in categories) {
<label class="checkbox">
<input type="checkbox" name="categories" value="@c.CategoryId"> @c.CategoryName
</label>
}
</div>
back in your Controller
[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");
}
Answer suggested by @balexandre above works great. However, I used following HTML Extension for CheckBoxList.
1. CheckboxList in ASP.net MVC4
2. Source Code:HTML Extension Helper method (Github)
The Major advantage of using this helper method is clean code and better readability. E.g.
@Html.CheckBoxListFor(model => model.SelectedItems, Model.AllItems)