Maintain state of a dynamic list of checkboxes in ASP.NET MVC

I got it working after much playing around with the various different approaches.

In the view:

<%string[] PostFeatures = Request.Form.GetValues("Features");%>
<% foreach (var Feature in (ViewData["AllPropertyFeatures"] as 
                             IEnumerable<MySolution.Models.PropertyFeature>)) 
   { %>
    <input type="checkbox" name="Features"
        id="Feature<%=Feature.PropertyFeatureID.ToString()%>" 
        value="<%=Feature.PropertyFeatureID%>" 
        <%if(PostFeatures!=null) 
          {
             if(PostFeatures.Contains(Feature.PropertyFeatureID.ToString()))
             { 
                Response.Write("checked=\"checked\""); 
             }
          }
        %> />
    <label for="Feature<%=Feature.PropertyFeatureID%>">
          <%=Feature.Description%></label>   <%
   }  %>

In the receiving controller method:

public ActionResult SearchResults(int[] Features)

This method has a number of advantages:

  • Allows labels to be clicked to toggle the corresponding checkboxes (usability).
  • Allows the Controller method to receive a super tidy array of ints, which ONLY contains the ints that have been selected – and not a whole other pile of items which were unselected or containing false/null/blank/0 etc.
  • Retains the checkbox’s checked state when the page reloads containing the form, i.e. the user’s selection is retained.
  • No random/stray type=hidden input fields created from the default ASP.Net MVC Html.CheckBox helper – I know it does those for a good reason, but in this instance, I don’t require them as I only want to know about which IDs have been selected and for those to be in a single, tidy int[].
  • No masses of additional server side bloated classes, helpers and other happy mess required to achieve such a simple thing.

I would recommend this approach for anyone wanting the cleanest / bloat-free solution for a dynamic checkbox list where you need the IDs and you just want to get down to business!

Leave a Comment