Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add a "Please select" item to a dropdown box in asp.net mvc

i have the following code in an asp.net mvc view.

<% = Html.DropDownList("Filter", new SelectList(Model.Items, "Id", "Name", 0), new { @id = "Filter", @class = "autoComplete1" })%>

i want to add an element at the top of the dropdown as the first item that says, "Please select".

do i have to add that into my Model.Items or is there a way i can add that element into the view and ignore the selection of that first element ??

like image 313
leora Avatar asked Apr 15 '10 19:04

leora


People also ask

How do I bind a dropdown in MVC Razor?

Binding MVC DropDownList with Static Values Just add an Html helper for DropDownList and provide a static list of SelectListItem. The values added as SelectListItem will be added and displayed in the DropDownList. In this way, you do not need to add anything to Controller Action.

What is SelectListItem MVC?

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


1 Answers

You can do:

<% = Html.DropDownList("Filter", new SelectList(Model.Items, "Id", "Name", 0), "Please Select", new { @id = "Filter", @class = "autoComplete1" })%>

Its a little long to read, but the method signature is:

DropDownList(name, IEnumerable<SelectListItem>, optionLabel, htmlAttributes)
like image 153
Sailing Judo Avatar answered Oct 13 '22 11:10

Sailing Judo