Add null value to DropDownList in ASP.net MVC

I create a data entry interface and successfully bind columns that have reference tables for their data using DropDownList, so the user selects from pre-configured values.

Now my problem is that I do not want the first value to be selected by default, I need to force the user to select a value from the list to avoid errors when they did not select this field and a default value was assigned.

Is there a more elegant way to do this than adding code to include an empty value at the top of the list after retrieving it from the database and before passing it to the SelectList constructor in the controller class?

+49
drop-down-menu asp.net-mvc
Jun 02 '09 at 22:33
source share
2 answers

The Html helper function accepts the "first empty value" parameter as the third argument.

<%=Html.DropDownList("name",dataSource,"-please select item-")%> 
+98
Jun 02 '09 at 22:45
source share

You can also use this method:

 dropdownlist.DataTextField = ds.Tables[0].Columns[0].Caption; dropdownlist.DataValueField = ds.Tables[0].Columns[1].Caption; dropdownlist.DataSource = ds; dropdownlist.DataBind(); dropdownlist.Items.Insert(0, new ListItem("Select ...", string.Empty)); 
-9
Aug 02 '09 at 20:04
source share



All Articles