tags:

views:

60

answers:

1

Hi

I have a dropdown that i need to set the default selected value from the database.

Example:

<%= Html.DropDownList("state", " -- Select one -- ")%>

The above code binds records from the ViewData["specialty"] from my entity model. And "Select One" is added on the top. Now if i need my dropdown to set the default value to 'NY'. How can i do that?

Appreciate your responses.

Thanks

A: 

Pass in a SelectList in the ViewModel

ViewData["States"] = new SelectList(states, "State_ID", "Name", "State_ID");

then

<%= Html.DropDownList("State_ID", (IEnumerable<SelectListItem>)ViewData["States"])%>
Wil
OK, but how does that set the default value?
Robert Harvey
The last parameter to the SelectList constructor in Wil's example would set the selected value to the item with a value of "State_ID". If your list contained state names with abbreviations as their respective values, you would do the following: ViewData["States"] = new SelectList(states, "State_ID", "Name", "OH") to select Ohio.
KOTJMF
Awesome. This worked for me. But the only thing is now i need to add "Select one" text to the selectList.
Rita