mvc: How do I add a initial Item to a DropDownList with Key of 0 and Description of 'Show All'
Here is an extract of my FormViewModel :
public SummaryFormViewModel(IEnumerable<Site> sites, IEnumerable<Landowner> landowners)
{
var sitesValues = sites
.OrderBy(s => s.SiteDescription)
.Select(s => new KeyValuePair<int, string>(s.SiteId, s.SiteDescription));
this.Sites = new SelectList(sitesValues, "Key", "Value");
I'd like to insert (as the first item) a value that will automatically be the default. It is to have a key of 0 and a description of 'Show All'
Basically开发者_StackOverflow社区 i'm offering combo boxes to the user to allow them to filter results.
I'm needing a neat way to add this initial row to the SelectList
Can anyone Advise me please, thanks in Advance
J
You can use .ToList() then .Insert() to add in a new value.
Example:
var sitesValues = sites
.OrderBy(s => s.SiteDescription)
.Select(s => new KeyValuePair<int, string>(s.SiteId, s.SiteDescription))
.ToList();
sitesValues.Insert(0, new KeyValuePair<int, string>(0, "Show All"));
this.Sites = new SelectList(sitesValues, "Key", "Value");
One of the overloads of the HTML.Dropdown method accepts a label for the first item. Something like:
Html.Dropdown("MyDropdown", Model.Sites, "Show All")
See http://msdn.microsoft.com/en-us/library/dd492883.aspx
精彩评论