I am developing an ASP.Net MVC 3 Web application and I am having some difficulties with getting the values from a checkboxlist. I have already read most of the questions on Stackoverflow around this area, however, I am still having some issues.
I have a ViewModel
public class ViewModelCheckBox
{
public string Id { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }
}
Another ViewModel which use the viewmodel above
public class ViewModelAssignSubSpeciality
{
public ListItem Item { get; set; }
public IList<ViewModelCheckBox> SpecialityList { get; set; }
}
Then in my controller
public ActionResult AssignSubSpeciality(int id)
{
//Get a list of all sub-specialities
var SpecialityList = _listService.GetListItemsByID(3).ToList();
//Get a list of sub-specialities for the the passed in id, this is either the id of a speciality or grade
IList<RelationshipSpecialitySub> assignedSpecialities = _listService.GetAssignedSubSpecialities(id).ToList();
var checkBoxList = new List<ViewModelCheckBox>();
foreach (ListItem item in SpecialityList)
{
ViewModelCheckBox chkBox = new ViewModelCheckBox { Id = item.listItemID.ToString(), Name = item.description };
//If sub-speciality exists in assignedSpecialities list, then make checkbox checked
foreach (var specilaity in assignedSpecialities)
{
if (specilaity.subID == item.listItemID)
{
chkBox.Checked = true;
}
else
{
chkBox.Checked = false;
}
}
checkBoxList.Add(chkBox);
}
ViewModelAssignSubSpeciality viewModel = new ViewModelAssignSubSpeciality();
viewModel.ListItem = _listService.GetListItemByID(id);
viewModel.SpecialityList = checkBoxList;
return View(viewModel);
}
The code in the controller above is getting a list of all the possible checkbox list items, then getting a list of all the previously selected checkbox list items for which it sets the checked option to true.
My View then looks like this, looping over the SpecialityList and creating a checkbox for each item, and also setting its selected value to true if needs be.
<fieldset>
<legend>Specialities</legend>
@foreach (var item in Model.SpecialityList)
{
<input type="checkbox" id="@item.Id" name="@item.Name" value="@item.Id" @(item.Checked ? "checked" : "") />
<label for="@item.Id">@item.Name</label><br />
}
<input type="submit" value="Save Changes" class="sepH_b" />
My HttpPost method in my controller then looks like this
public ActionResult AssignSubSpeciality(ViewModelAssignSubSpeciality model)
{
//delete all sub-specialities in tbl relationshipSpecialitySub for List
foreach (ViewModelCheckBox item in model.SpecialityList)
{
//_listService.DeleteSubSpecialityFromSpeciality(item.Id);
}
return RedirectToAction("ListItems", new { id = model.ListItem.listID });
}
However, when I try to get the selected checkboxes in
model.SpecialityList
It us always null. I am not sure why it doesnt contain a list of ViewModelCheckBox.
Can anyone please help me with this?
Thank you.