views:

243

answers:

2

Hello, 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.

+1  A: 

Autobinding the selected item

The other approach is to automatically bind the selected item, and passing the list of items as parameter to the DropDownList helper method.

In the controller you do exactly the same thing as before, just don’t set to true the Selected property of any item. Then you also have to put into the view model the value of the item you want to select.

var model = new IndexViewModel()
            {
                ListItems = items,
                SelectedItem = 2
            };

And finally in the view, you use the overload which accepts also the selectList parameter:

<%= Html.DropDownList("SelectedItem", Model.ListItems) %>

The only difference in the HTML rendered is that, with first approach, the name of the HTML select element is ListItems, with the second it is SelectedItem.

These approaches are fine if you are creating your own list, but they are not the optimal solution if you are receiving the list of options for an external method, for example from a DB repository.

Take a look at this link

ali62b
+1  A: 

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.

Rashmi Pandit