R – HTML.DropDownList does not respect pre-selected value

asp.net-mvcdrop-down-menu

I want to use Html.DropDownList(string name, IEnumerable SelectList, Object htmlAttributes) to render a select list with a preselected value for me.

My select list is in the model object of my view, so I have been writting the following code:

<%= Html.DropDownList("aName", mySelectList, new { }) %>

Which will render the select list without the pre-selected value.

A workaround I have found is passing the SelectList as ViewData and doing the following:

In the controller:

ViewData["TimeZones"] = mySelectList;

In the view:

<%= Html.DropDownList("TimeZones", null, new { }) %> 

This way the select list will be rendered with the preselected value, however, I don't want to be forced to pass my select list as view data. What am I doing wrong? Thank you in advance for your help.

Best Answer

You can simply do this (it works):

<%: Html.DropDownList("DropdownName", new SelectList(ListItems, "Value", "Text", selectedItem), htmlAttributes)%>

Let me know in case this does not work for you.