I have a drop down on my site that has a number of languages in it. When a user selects a different language, the page text reloads to that language. I would like the language drop down to change to reflect that by specifying the selected index of the selected language. However when ever I do this, the drop down in HTML does not change and always displays the first item in the list.
I have the following ViewModel :
public class BaseViewModel
{
public BaseViewModel()
{
}
public IEnumerable<SelectListItem> LanguageSelectListItems { get; set; }
}
The LanguageSelectListItems property is populated successfully when I construct a list of SelectListItems. When this is passed into the view, the selected language SelectListItem is set to true - in this case Swedish. All good so far.
But when the view calls Html.DropDownList() the selected languages' selected property changes to false. A couple of pictures might explain this better.
Before calling @Html.DropDownList("language", Model.LanguageSelectListItems)

Immediately after @Html.DropDownList("language", Model.LanguageSelectListItems)

You can see that the Selected property for the Swedish language has changed to false on the SelectListItem, and this is the resultant HTML :
<select name="language" id="language">
<option value="2">English</option>
<option value="3">Finnish</option>
<option value="4">Swedish</option>
</select>
Any ideas why this might be happening ?
Edit: LanguageSelectListItems is being populated and the selected language being set using this function (where languages is an enumerable of language) :
public static IEnumerable<SelectListItem> GetLanguageList(int selectedIndex)
{
var selectListItems = new List<SelectListItem>();
foreach (var language in languages)
{
selectListItems.Add(new SelectListItem() { Text = language.Name, Value = language.Id });
}
if (selectedIndex >= 0)
{
selectListItems[selectedIndex].Selected = true;
}
return selectedListItems;
}