11
I'm trying to model bind a set of dynamically generated checkboxes so as to process them in the controller action but can't get the model binding to occur. This is the scenario:
My ViewModel class (DocumentAddEditModel) contains a dictionary (Dictionary<string,bool>) with the string of each entry being the name/label for each checkbox and the boolean indicating whether the checkbox is checked:
public class DocumentAddEditModel
{
...
private Dictionary<string, bool> _categoryCheckboxes = new Dictionary<string,bool>();
...
...
public Dictionary<string, bool> CategoryCheckboxes
{
get { return _categoryCheckboxes; }
set { _categoryCheckboxes = value; }
}
...
}
}
Within my controller the action that handles the GET request for the form populates the dictonary as follows:
public class DocumentsController : Controller
{
[RequiresAuthentication]
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Add()
{
DocumentAddEditModel documentAddEditModel = new DocumentAddEditModel();
...
Dictionary<string, bool> categoryCheckboxes = new Dictionary<string, bool>();
...
string[] categories = Enum.GetNames(typeof(Category));
foreach (string category in categories)
categoryCheckboxes.Add(category, false);
documentAddEditModel.CategoryCheckboxes = categoryCheckboxes;
return View(documentAddEditModel);
}
}
Within the view i have the following to generate the checkboxes:
<% foreach (KeyValuePair<string, bool> categoryCheckbox in ViewData.Model.CategoryCheckboxes)
{%>
<input class="checkbox" type="checkbox" name="CategoryCheckboxes[0].Key" id="<%= categoryCheckbox.Key %>" />
<label class="categoryLabel" for="<%= categoryCheckbox.K