Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DropdownListFor default value

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

like image 401
user517406 Avatar asked Aug 29 '11 11:08

user517406


People also ask

How to set default value to DropDownListFor in html?

The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.

What is DropDownListFor?

DropDownListFor will automatically select the selected value by using the specified property: // Will select the item in model. Equipments that matches Model. EquipmentId @Html.

What is SelectListItem MVC?

SelectListItem is a class which represents the selected item in an instance of the System. Web. Mvc.


1 Answers

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.

like image 144
itsmatt Avatar answered Oct 09 '22 01:10

itsmatt