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 scenari
If you are binding your checkboxes to a Dictionary<string, bool>
try this:
<% var i = 0; %>
<% foreach (KeyValuePair<string, bool> categoryCheckbox in Model.CategoryCheckboxes) {%>
<input type="hidden" name="<%= String.Format("CategoryCheckboxes[{0}].Key", i) %>" value="<%= categoryCheckbox.Key %>" />
<%= Html.CheckBox(String.Format("CategoryCheckboxes[{0}].Value", i), categoryCheckbox.Value) %>
<label class="categoryLabel" for="<%= categoryCheckbox.Key %>"><%= categoryCheckbox.Key %></label>
<% i++; %>
<% } %>
Hope this helps
UPDATED:
For binding to IDictionary<T1, T2>
your form must contain inputs with "CategoryCheckboxes[n].Key" and "CategoryCheckboxes[n].Value" Ids/Names, where n must be zero-based and unbroken.
Something simpler:
@foreach (var pair in Model.CategoryCheckboxes)
{
@Html.CheckBoxFor(m=>m.CategoryCheckboxes[pair.Key])
}
hidden elements are the modus operandi of asp.net. in the webforms version it was the ViewState, which was a massive hidden field, in the MVC its lighter weight more straightforward hidden fields per control. I'm not sure what's wrong or disturbing about that. Somehow you have to keep state, you can either do it client side or server side. I suggest client side for non-sensitive information that way it will still be there if the server is restarted between postbacks etc.