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
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
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;
I needed a dropdown in a editable grid myself with preselected dropdown values. Afaik, the selectlist data is provided by the controller to the view, so it is created before the view consumes it. Once the view consumes the SelectList, I hand it over to a custom helper that uses the standard DropDownList helper. So, a fairly light solution imo. Guess it fits in the ASP.Net MVC spirit at the time of writing; when not happy roll your own...
public static string DropDownListEx(this HtmlHelper helper, string name, SelectList selectList, object selectedValue) { return helper.DropDownList(name, new SelectList(selectList.Items, selectList.DataValueField, selectList.DataTextField, selectedValue)); }
Is it possible to pass more than one Selected Values??? (This is the case where the control is not DropDownList but a ListBox with multiple Selected Items)