DropdownListFor default value
Is there a simple way to add a "--Please select--" default option to a DropDownListFor in 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.
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",""))
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>