Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is default value for "optionLabel" of the HTML DropDownList?

So if Set up a DropDownList where Text: "people names" (string)and Value:studentID (int). in my view like this (assuming myDDL is data from code-behind placed in the viewbag)

     @Html.DropDownList("myDDL", (IEnumerable<SelectListItem>)ViewBag.myDDL,  
     "Select Stuff", new Dictionary<string,object>{
      {"class","dropdowns"},{"id","myDDL"}})  

What is the value of "Select Stuff" which is an optional label that appears at the beginning of the dropdown list?

I'd like the value because it if no value is selected then I'd like to get all the data.

Thanks!

like image 772
EKet Avatar asked Jan 17 '12 23:01

EKet


2 Answers

It's empty and it's always the first option of the dropdown, so make sure that you are binding it to a non-nullable property in the postback action:

<select name="selectedValue">
    <option value="">Select Stuff</option>
    ...
</select>

Also you seem to be using myDDL as both the first argument and the second of the dropdownlist helper which is wrong. The first argument is a property that would be used to get the selected value. The second is the available values and must be an IEnumerable<SelectListItem>.

So something like this would make more sense:

@Html.DropDownList(
    "selctedValue",
    (IEnumerable<SelectListItem>)ViewBag.myDDL,
    "Select Stuff", 
    new { @class = "dropdowns", id = "myDDL" }
)

But what would really make sense and what I would recommend you is to get rid of this ViewBag and use a view model and the strongly typed version of this helper:

@model MyViewModel
...
@Html.DropDownListFor(
    x => x.SelectedValue,
    Model.MyDdlItems,
    "Select Stuff", 
    new { @class = "dropdowns", id = "myDDL" }
)
like image 193
Darin Dimitrov Avatar answered Nov 18 '22 06:11

Darin Dimitrov


It's the empty string. The documentation covers this (emphasis mine):

optionLabel

Type: System.String

The text for a default empty item. This parameter can be null.

like image 2
Jon Avatar answered Nov 18 '22 08:11

Jon