tags:

views:

33

answers:

2

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 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

+1  A: 

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");
envalid
A: 

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

AUSteve
If that defaults to value="" then that would probable be ideal. Use `int?` and check `.HasValue`. Much more efficient and clear if it works out.
envalid
Yes, it's value is empty string
AUSteve
Of course, thanks for the help, does anyone know how to mark Questions as answered? Cannot see any options on the page.
John
@John: click the tick outline beside the relevant answer, it will go green and the question will be marked as answered.
AUSteve