tags:

views:

547

answers:

4

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

A: 

You will need to use JQuery.

Check this question

Konstantinos
I don't want to handle this on client side. I need to set it on server side after selectlist initialization..
kaivalya
+3  A: 

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;
womp
Thanks, i will mark as answer if there is no other solution - i was expecting there was a builtin way to set it instead of iterating on the items
kaivalya
The SelectedValue property of SelectList is readonly simply because there is no guarantee of uniqueness... you really have to deal with it at the item level as far as I know.
womp
A: 

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));
}
Erik Lenaerts
A: 

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)

FaN