MVC Dropdownlistfor defaulting to previously selected value when using a single SelectListItem List

Watch out for this one. If you have created a single list of SelectListItems and use this viewModel property to populate multiple DropDownListFor HTML helper controls, you will likely notice some strange behaviour.

What happens is that if one DropDownListFor has a selected value (ie. its bound property isn’t null) all subsequent DropDownListFor which are populated using the same SelectListItem List and don’t have a selected value have their default selection changed to whatever the previously selected value was. This happens even though expected behaviour would be to just leave the subsequent DropDownListFor selected to their default values.

As an example, this problem has the potential to occur below. If BirthCountry was selected to say Canada, and ResidenceCountry had no value, the 2nd dropdown would be defaulted to Canada and not “” as explicitly specified.

public IEnumerable<SelectListItem> Countries {get;set;}
@Html.DropDownListFor(x=>x.BirthCountry,Model.Countries,"") @Html.DropDownListFor(x=>x.ResidenceCountry,Model.Countries,"")

This is because SelectListItem is a reference type so when you change the Selected property to true, all dropdowns which use that SelectListItem will reflect this.

Always use distinct SelectListItem lists for each DropDownListFor

You can do this by creating them in the viewModel like:

public IEnumerable<SelectListItem> BirthCountries {get;set;}
public IEnumerable<SelectListItem> ResidenceCountries {get;set;}
@Html.DropDownListFor(x=>x.BirthCountry,Model.BirthCountries,"") @Html.DropDownListFor(x=>x.ResidenceCountry,Model.ResidenceCountries,"")

or just have a single viewModel property which is a collection of countries and then create multiple SelectListItems in your razor view:

public IEnumerable<Country> Countries { get;set}
@Html.DropDownListFor(x=>x.BirthCountry, 
    new SelectList(Model.Countries,"countryCode","countryName", Model.BirthCountry))
@Html.DropDownListFor(x=>x.ResidenceCountry, 
    new SelectList(Model.Countries,"countryCode","countryName", Model.ResidenceCountry))

Related links

Stackoverflow question with a good answer detailing when the behaviour described above occurs

Thread on forums.asp.net discussing whether this behaviour is a bug or not

Leave a Reply

Your email address will not be published. Required fields are marked *