How to handle checkboxes in ASP.NET MVC forms?

Html.CheckBox is doing something weird – if you view source on the resulting page, you’ll see there’s an <input type="hidden" /> being generated alongside each checkbox, which explains the “true false” values you’re seeing for each form element.

Try this, which definitely works on ASP.NET MVC Beta because I’ve just tried it.

Put this in the view instead of using Html.CheckBox():

<% using (Html.BeginForm("ShowData", "Home")) {  %>
  <% foreach (var o in ViewData.Model) { %>
    <input type="checkbox" name="selectedObjects" value="<%=o.Id%>">
    <%= o.Name %>
  <%}%>
  <input type="submit" value="Submit" />
<%}%>

Your checkboxes are all called selectedObjects, and the value of each checkbox is the GUID of the corresponding object.

Then post to the following controller action (or something similar that does something useful instead of Response.Write())

public ActionResult ShowData(Guid[] selectedObjects) {
    foreach (Guid guid in selectedObjects) {
        Response.Write(guid.ToString());
    }
    Response.End();
    return (new EmptyResult());
}

This example will just write the GUIDs of the boxes you checked; ASP.NET MVC maps the GUID values of the selected checkboxes into the Guid[] selectedObjects parameter for you, and even parses the strings from the Request.Form collection into instantied GUID objects, which I think is rather nice.

Leave a Comment