DropDownListFor does not select value if in for loop

Eyeslandic picture Eyeslandic · Apr 13, 2010 · Viewed 14.6k times · Source

In my view

<%= Html.DropDownListFor( x => x.Countries[ i ], Model.CountryList )%>

in my controller

public int[ ] Countries { get; set; }

public List<SelectListItem> CountryList { get; set; }

When the forms gets posted there is no problem, the dropdown is populated and the values the user selects are posted. But when I try to load the form with already assigned values to the Countries[ ] it does not get selected.

Answer

Nick picture Nick · Apr 9, 2013

Not sure if this is new to mv4 or if it exists in prior version. But the DropDownListFor includes an additional parameter for the SelectList Constructor.

SelectList(IEnumerable, String, String, Object)

For example:

Html.DropDownListFor( x => x.Countries[ i ], New SelectList(Model.CountryList,"ID","Description",Model.Countries[i]))

Where ID is the Country ID in the CountryList object and Description is the Country Name.