DropdownListFor default value

asp.net Mvc-3

asp.net Mvc-3 Problem Overview


Is there a simple way to add a "--Please select--" default option to a DropDownListFor in MVC 3?

asp.net Mvc-3 Solutions


Solution 1 - asp.net Mvc-3

So, I did something like this:

@Html.DropDownListFor(model => model.Dessert, 
                      new SelectList(Model.AvailableDesserts, "DessertID", "DessertName"),
                      "---Select A Dessert ---")

Seems to work pretty well. Dessert in my viewmodel is the one selected by the user. AvailableDesserts is a collection of ones to pick from. Hope that helps.

Solution 2 - asp.net Mvc-3

I have a couple extension methods on SelectList

    public static SelectList PreAppend(this SelectList list, string dataTextField, string selectedValue, bool selected=false)
    {
        var items = new List<SelectListItem>();
        items.Add(new SelectListItem() { Selected = selected, Text = dataTextField, Value = selectedValue });
        items.AddRange(list.Items.Cast<SelectListItem>().ToList());
        return new SelectList(items, "Value", "Text");
    }
    public static SelectList Append(this SelectList list, string dataTextField, string selectedValue, bool selected=false)
    {
        var items = list.Items.Cast<SelectListItem>().ToList();
        items.Add(new SelectListItem() { Selected = selected, Text = dataTextField, Value = selectedValue });
        return new SelectList(items, "Value", "Text");
    }
    public static SelectList Default(this SelectList list,string DataTextField,string SelectedValue)
    {
        return list.PreAppend(DataTextField, SelectedValue, true);
    }

Then my razor looks like:

@Html.DropDownListFor(m=>m.SelectedState, 
    Model.StateList().Default("Select One",""))

Solution 3 - asp.net Mvc-3

Hi what about trying this (in case you use DisplayFor method)

private IEnumerable<SelectListItem> AddDefaultOption(IEnumerable<SelectListItem> list, string dataTextField, string selectedValue)
    {
        var items = new List<SelectListItem>();
        items.Add(new SelectListItem() { Text = dataTextField, Value = selectedValue});
        items.AddRange(list);
        return items;
    }

Then just add this code to your Controller

//lambda expression binding
ViewBag.YourList = db.YourTable.Select(x => x).ToList().Select(x => new SelectListItem
        {
            Value = x.Id.ToString(),
            Text = x.DisplayName.ToString()
        });

        ViewBag.YourList = AddDefaultOption(ViewBag.YourList, "Select One...", "null", true);

And finally at the View you could display a dropdown, combobox just like this

    <div class="editor-label">
        Your Label
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.ForeignKey, (IEnumerable<SelectListItem>)ViewBag.YourList)
    </div>

Solution 4 - asp.net Mvc-3

I wanted to set the default value to whatever was passed in as a Url Parameter called SiteType:

    <div class="form-group">
        @Html.LabelFor(model => model.Type, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Type, ChangeOrderSite.SiteTypeNames.Select(s => new SelectListItem { Text = s.Value, Value = s.Key.ToString(), Selected = s.Key.ToString() == Request["SiteType"] }), new { @class = "control-label col-md-2" })
            @Html.ValidationMessageFor(model => model.Type)
        </div>
    </div>

My drop down is a list of Site Types.

Solution 5 - asp.net Mvc-3

I like the following method:

@Html.DropDownListFor(m => m.SelectedId, new SelectList(Model.Items, "Id", "Name"), new SelectListItem() { Text = "None", Value = "", Selected = true }.Text, new { @class = "form-control search-select-input btn btn-block btn-outline-secondary dropdown-toggle p-1" })

Where Items is an IEnumerable of type you want to display in the dropdown. And you can change out whatever bootstrap classes you want in the last parameter.

This way allows you to set a default label and specify the value of the label if needed.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser517406View Question on Stackoverflow
Solution 1 - asp.net Mvc-3itsmattView Answer on Stackoverflow
Solution 2 - asp.net Mvc-3asawyerView Answer on Stackoverflow
Solution 3 - asp.net Mvc-3jonbarloView Answer on Stackoverflow
Solution 4 - asp.net Mvc-3RhyousView Answer on Stackoverflow
Solution 5 - asp.net Mvc-3RUDYLIB926View Answer on Stackoverflow