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

橙三吉。 提交于 2019-11-27 14:08:36
Aaron

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!

The problem is that when you are rendering your list of checkboxes, you aren't setting any of them as selected. You will need to set your int[] Features in ViewData, and then in your foreach loop, check to see if the ID of that Feature is in the array in ViewData.

something like:

<%=Html.CheckBox("Features", 
    ((int[])ViewData["SelectedFeatures"]).Contains(Feature.PropertyFeatureID),
    new { @id = Feature.PropertyFeatureID, @value = Feature.PropertyFeatureID })%

although I didn't test it, so it might not be 100%.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!