MVC - Set selected value of SelectList
Solution 1:
If you have your SelectList object, just iterate through the items in it and set the "Selected" property of the item you wish.
foreach (var item in selectList.Items)
{
if (item.Value == selectedValue)
{
item.Selected = true;
break;
}
}
Or with Linq:
var selected = list.Where(x => x.Value == "selectedValue").First();
selected.Selected = true;
Solution 2:
A bit late to the party here but here's how simple this is:
ViewBag.Countries = new SelectList(countries.GetCountries(), "id", "countryName", "82");
this uses my method getcountries to populate a model called countries, obviousley you would replace this with whatever your datasource is, a model etc, then sets the id as the value in the selectlist. then just add the last param, in this case "82" to select the default selected item.
[edit] Here's how to use this in Razor:
@Html.DropDownListFor(model => model.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries, new { @class = "form-control" })
Important: Also, 1 other thing to watch out for, Make sure the model field that you use to store the selected Id (in this case model.CountryId) from the dropdown list is nullable and is set to null on the first page load. This one gets me every time.
Hope this saves someone some time.