Reputation: 32798
I have the following viewmodel:
public class CityViewModel
{
public CityViewModel() {
CityDetails = Enumerable.Range(1,2).Select(x => new CityDetail()).ToList();
}
public City City { get; set; }
public IList<CityDetail> CityDetails { get; set; }
public class CityDetail
{
public CityDetail() {
Correct = true;
}
public bool Correct { get; set; }
}
In my view I have the following:
@foreach (int index in Enumerable.Range(0, Model.CityDetails.Count()))
{
<input type="hidden" name="CityDetails[@index]_Correct)" value="false" />
<input type="checkbox" id="CityValid" name="CityDetails[@index]_Correct" value='@Model.CityDetails[index].Correct' />
I can't get any binding from the view to the model for the field named "Correct" so I am wondering about the naming that I used. Does anyone have an idea what might be wrong?
Upvotes: 0
Views: 295
Reputation: 4485
The easy and best way to map collection is using the indexer. Use the following code snippet
@for (int i = 0; i < Model.CityDetails.Count; i++)
{
@Html.EditorFor(x => Model.CityDetails[i].Correct)
}
Upvotes: 2
Reputation: 8562
There's no need for your view to look like that. Create an editor template, and then use Html.EditorFor(x => x.CityDetails). That will handle enumerating the collection and properly writing out the elements so that they map back into the list.
Upvotes: 1