I need to be able to build a dynamic list of dropdowns in an ASP MVC 3 project. My model contains the following:
public IList<Collections.Division> Divisions { get; set; }
public SelectList DivisionSelectList
{
get
{
DivisionRepository repo = new DivisionRepository();
var divisions = repo.Divisions;
return new SelectList(divisions,"DivisionId","DivisionName");
}
}
And the Division class looks like this:
public class Division
{
public int DivisionId { get; set; }
}
I build a list of dropdowns in the view like this:
@for(int i = 0;i< Model.Divisions.Count;i++)
{
@Model.Divisions[i].DivisionId //for debug only
@Html.DropDownListFor(x=>x.Divisions[i].DivisionId,Model.DivisionSelectList)
<br/>
}
The list of divisions is populated before rendering the view and I can see the data looks correct but the dropdowns items are not being selected. Does anyone know why?
This looks like a bug in MVC, see here:
DropDownListFor not binding on Edit View with repeating items (List<T>)
I had to do this: