kaivalya kaivalya - 4 years ago 314
C# Question

MVC - Set selected value of SelectList

How can I set the selectedvalue property of a SelectList after it was instantiated without a selectedvalue;

SelectList selectList = new SelectList(items, "ID", "Name");

I need to set the selected value after this stage

Answer Source

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;

Or with Linq:

var selected = list.Where(x => x.Value == "selectedValue").First();
selected.Selected = true;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download