CheckboxFor does not bind to nested objects

Is CheckBoxFor unlimited when a property is defined in an object nested in a model?

Here is an example. I have a SearchOptions model that contains a List<Star> property. Each Star has a number, a name, and a bool property, which should be limited:

 public class SearchOptions { public SearchOptions() { // Default values Stars = new List<Star>() { new Star() {Number=1, Name=Resources.Home.Index.Star1, IsSelected=false}, new Star() {Number=2, Name=Resources.Home.Index.Star2, IsSelected=false}, new Star() {Number=3, Name=Resources.Home.Index.Star3, IsSelected=true}, new Star() {Number=4, Name=Resources.Home.Index.Star4, IsSelected=true}, new Star() {Number=5, Name=Resources.Home.Index.Star5, IsSelected=true}, }; } public List<Star> Stars { get; set; } } 

In my strongly typed view (from SearchOptions ), I end with the Stars property:

 @using (Html.BeginForm("Do", "Home")) { <fieldset> <legend>@MVC3TestApplication.Resources.Home.Index.Search</legend> @{ foreach (Star s in Model.Stars) { @Html.CheckBoxFor(m => s.IsSelected) <label>@s.Name</label> }} </fieldset> <input type=submit value="Invia" /> } 

Controller (corresponding part):

  public ActionResult SearchOptions() { return View(new SearchOptions()); } [HttpPost] public ActionResult Do(SearchOptions s) { // Do some stuff return View("SearchOptions", s); } 
+4
source share
1 answer

This is because of how you access the properties in the CheckBoxFor expression.

 @for (int i = 0; i < Model.Stars.Count(); i++) { @Html.CheckBoxFor(m => m.Stars[i].IsSelected) <label>@Model.Stars[i].Name</label> } 

This should work for you.

Here is the conclusion from different methods:

 //using the for loop <input id="Stars_2__IsSelected" name="Stars[2].IsSelected" type="checkbox" value="true" /> //using the foreach <input checked="checked" id="s_IsSelected" name="s.IsSelected" type="checkbox" value="true" /> 

You will notice that foreeach does not contain the correct name to match it when binding the model.

+6
source

All Articles