CheckBoxFor is not bounded when a property is defined in an object nested in the 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 that should be bounded:
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 (of SearchOptions) i loop over 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" />
}
The (relevant part of) controller is:
public ActionResult SearchOptions()
{
return View(new SearchOptions());
}
[HttpPost]
public ActionResult Do(SearchOptions s)
{
// Do some stuff
return View("SearchOptions", s);
}
View(model)?Do (SearchOptions s)shows thatshas old (default) values, even if i check/uncheck all the checkboxes. Thanks for helping,CheckBoxFor()sets it's name values tos.IsSelectedrather thanModel.Star[].IsSelected. I'll see what I can do or someone else will post the answer before me :)