ASP.NET MVC DropDownListFor does not honour SelectListItem.Selected

William Niu picture William Niu · Jul 14, 2011 · Viewed 8.1k times · Source

I am using DropDownListFor to render a dropdown list in a view. Somehow the rendered list does not select the SelectListItem with Selected set to true.

In the controller action:

var selectList = sortedEntries.Select(entry => new SelectListItem
                            {
                                Selected = entry.Value.Equals(selectedValue),
                                Text = entry.Value,
                                Value = entry.Id
                            });

return View(new DropDownListModel
            {
                ListId = id,
                SelectList = selectList,
                OptionLabel = "Click to Select"
            });

In the view:

<%= Html.DropDownListFor(m => m.ListId, 
    Model.SelectList, 
    Model.OptionLabel, 
    new {@class="someClass"}) %>

I have tried the following:

  1. make sure that there is one and only one items with Selected set to true.
  2. remove the option label argument.
  3. remove the HTML attribute object.
  4. use SelectList in DropDownListFor:

   Html.DropDownListFor(m => m.ListId, 
        new SelectList(Model.SelectList, "Value", "Text", 
             new List<SelectListItem>(Model.SelectList).Find(s => s.Selected)), 
        new {@class="someClass"})

Any suggestions as to what went wrong?

EDIT:

more information:

  • This action is a child action, called by another view with HTML.RenderAction

Answer

John Landheer picture John Landheer · Jul 14, 2011

DropDownListFor will always select the value that the listbox is for, so in this case it will look at the value of ListId and make that item in the list selected. If ListId is not found in the list, the first item (or default text) will be selected. If you want a list that selects based on the selected attribute use DropDownList (without the For, in that case you have to name it yourself).

So in your case this would work:

var selectList = sortedEntries.Select(entry => new SelectListItem
{
    Text = entry.Value,
    Value = entry.Id
});

return View(new DropDownListModel
{
    ListId = selectedValue,
    SelectList = selectList,
    OptionLabel = "Click to Select"
});