Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC DropDownListFor does not honour SelectListItem.Selected

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
like image 261
William Niu Avatar asked Jul 14 '11 06:07

William Niu


2 Answers

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"
});
like image 181
John Landheer Avatar answered Sep 21 '22 15:09

John Landheer


I got the same problem on the same model (with the other models in the decision no problem)

Does not work:

@Html.DropDownListFor(o => o.Drivers.ValueListItems.Value, Model.Drivers.ValueListItems, new { size = Model.Drivers.ValueSizeList, Multiple = "multiple" })

Works perfectly, the elements selected:

@Html.DropDownListFor(o => o.Drivers.ValueListItems.ToDictionary(u=>u.Value).Values, Model.Drivers.ValueListItems, new { size = Model.Drivers.ValueSizeList, Multiple = "multiple" })
like image 27
Clevelus Avatar answered Sep 19 '22 15:09

Clevelus