title: Maintain state of a dynamic list of checkboxes in ASP.NET MVC
body: <p>I have a class called "PropertyFeature" which simply contains PropertyFeatureID and Description. It's a proper model created through LINQ to SQL mapped to an SQL Server database table. An example instance/row would be:</p>
  
  <pre><code>PropertyFeatureID: 2
  Description: "Swimming Pool"
  </code></pre>
  
  <p>The number of rows (PropertyFeatures) can of course grow and shrink, and so I want to dynamically render a list of checkboxes so that the user can select any of them.
  I can dynamically render the Checkboxes easily enough, with something like:</p>
  
  <pre><code>&lt;%foreach (var Feature in (ViewData["Features"] as IEnumerable&lt;MySolution.Models.PropertyFeature&gt;)) { %&gt;
  &lt;%=Html.CheckBox("Features", new { @id = Feature.PropertyFeatureID, @value = Feature.PropertyFeatureID })%&gt;&lt;label for="Feature&lt;%=Feature.PropertyFeatureID%&gt;"&gt;&lt;%=Feature.Description%&gt;&lt;/label&gt;
  &lt;%}%&gt;
  </code></pre>
  
  <p>I specify the ID for each checkbox and render the matching label so that the user can intuitively click the label and toggle the checkbox - that works great.</p>
  
  <p>I set the CheckBox's "name" to "Features" so all the checkboxes render with the same name, and the MVC Model Binder piles them into a single collection called "Features" when the form is posted. This works nicely.</p>
  
  <p>Once the form is submitted, I use the checked values and store them, so I need the actual integer values so I know which PropertyFeature is selected, not just a pile of Booleans and field names. So ideally, I want it as an array or a collection that's easy to work with.</p>
  
  <p>I am able to retrieve the selected values from within my Controller method when the button is clicked because I have specified the parameter as int[] Features.</p>
  
  <p><strong>But the problem</strong> is that it doesn't maintain state. That is, when I click the submit button and the page reloads (with the form again displayed) I want all of the dynamic checkboxes to retain their checked status (or not). All of the other fields that I've created with <code>Html.DropDownList</code> and <code>Html.TextBox</code> all maintain their states successfully no problems at all on the same page in the same form.</p>
  
  <p>I have spent hours reading all of the other threads and articles on similar issues and there is a lot of talk about using <code>ICollection</code> and <code>IDictionary</code> to bundle things up and include a Boolean value for each item so that it can maintain the checkbox state. But I don't 100% grasp how to use that in the context of my own personal example. I would like to keep the solution really simple and not have to code up pages of new classes just to maintain my checkbox state.</p>
  
  <p>What is the cleanest and proper way to do this?</p>