Binding a list of checkboxes from view to posted collection in ASP.NET MVC 2
- by mare
Given the code below within which I render a bunch of checkboxes in my view and the code for controller, someone please explain how can I get the values of the checkboxes (I need the key and the checked status) in the controller.
<% foreach (string mappingId in Model.Mappings) {%>
<tr><td>
<%=mappingId %><br />
<%=Html.Label("Checkbox_" + mappingId, "Sync?")%>
<%=Html.CheckBox("Checkbox_" + mappingId, true) %>
</td></tr>
<% } %>
[HttpPost]
public ActionResult Sync(FormCollection collection)
{
foreach (var posted in collection)
{
// here the "posted" variable shows up in the debugger as
// "Checkbox_AD0D1" as Value (AD0D1 being the key in my model) and of type "object"
// of course, this line fails but it shows what I want to do
bool currentCheckbox = (bool) posted;
}
return View();
}