ASP.NET MVC Multiple Checkboxes
asp.net-mvc, c#
Solution
Model:
public class MyViewModel
{
public int Id { get; set; }
public bool Available { get; set; }
}
Controller:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = Enumerable.Range(1, 20).Select(x => new MyViewModel
{
Id = x
});
return View(model);
}
[HttpPost]
public ActionResult Index(IEnumerable<MyViewModel> model)
{
...
}
}
View `~/Views/Home/Index.cshtml`:
@model IEnumerable<AppName.Models.MyViewModel>
@using (Html.BeginForm())
{
@Html.EditorForModel()
<input type="submit" value="OK" />
}
Editor template `~/Views/Home/EditorTemplates/MyViewModel.cshtml`:
@model AppName.Models.MyViewModel
@Html.HiddenFor(x => x.Id)
@Html.CheckBoxFor(x => x.Available)
Problem
I have a `List` of about 20 items I want to display to the user with a checkbox beside each one (a `Available` property on my ViewModel). When the form is submitted, I want to be able to pass the value of each checkbox that is checked back to my controller method via the `Selections` property on my ViewModel. How would I go about doing this using the Form Helper class in MVC? Is this even possible? PS: I don't want a listbox where the user can just highlight multiple items.