asp.net-mvcselectlist

How can I add an item to a SelectList in ASP.net MVC


Basically I am looking to insert an item at the beginning of a SelectList with the default value of 0 and the Text Value of " -- Select One --"

Something like

SelectList list = new SelectList(repository.func.ToList());
ListItem li = new ListItem(value, value);
list.items.add(li);

Can this be done?


Solution

  • There really isn't a need to do this unless you insist on the value of 0. The HtmlHelper DropDownList extension allows you to set an option label that shows up as the initial value in the select with a null value. Simply use one of the DropDownList signatures that has the option label.

    <%= Html.DropDownList( "DropDownValue",
                           (IEnumerable<SelectListItem>)ViewData["Menu"],
                            "-- Select One --" ) %>