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:
- make sure that there is one and only one items with
Selected
set totrue
. - remove the option label argument.
- remove the HTML attribute object.
- use
SelectList
inDropDownListFor
:
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
DropDownList
, which allows me to specify an ID for the select control, as well as a selected value in theSelectListItem
. Thanks for the explanation! – Manara