Reputation: 5105
I am developing an ASP.Net MVC 3 Web application and I am having difficulties retrieving the selected checkbox values within the HttpPost method in my Controller. Hopefully someone can help.
I have 2 ViewModels
public class ViewModelShiftSubSpecialties
{
public IEnumerable<ViewModelCheckBox> SpecialtyList { get; set; }
}
public class ViewModelCheckBox
{
public string Id { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }
public string Specialty { get; set; }
}
And a partial View I use as an EditorTemplate
@model Locum.UI.ViewModels.ViewModelCheckBox
@Html.HiddenFor(x => x.Id)
@Html.CheckBoxFor(x => x.Checked)
@Html.LabelFor(x => x.Name, Model.Name)<br />
In my View I create the checkboxes under two headings, Medicine and Surgery
<h3>Medicine</h3>
foreach (var sub in Model.SpecialtyList)
{
if (sub.Specialty.Equals("Medicine"))
{
@Html.EditorFor(m => sub)
}
}
<h3>Surgery</h3>
foreach (var sub in Model.SpecialtyList)
{
if (sub.Specialty.Equals("Surgery"))
{
@Html.EditorFor(m => sub)
}
}
And then in my HttpPost Controller I try to get the values of the selected checkboxes, but mode.SpecialtyList is always Null
[HttpPost]
public ActionResult AssignSubSpecialties(ViewModelShiftSubSpecialties model)
{
foreach (var item in model.SpecialtyList)
{
if (item.Checked)
{
//do some logic
}
}
return View();
}
Does anyone know why model.SpecialtyList is always Null?
Any help is much appreciated.
Thanks.
Upvotes: 1
Views: 1127
Reputation: 26930
give checkboxes same names like:
<input type="checkbox" name="ViewModelShiftSubSpecialties.SpecialtyList" .../>
and it will post an array
Upvotes: 3