Why doesn't DropDownListFor select correct options in a for loop?

  • Page Owner: Not Set
  • Last Reviewed: 2018-10-19

I have a list of items that need dropdowns. I'm rendering as such:

@for (var i = 0; i < Model.Items.Count; i++)
{
    <div class="row">
        <div class="col-md-4">
            @Html.LabelFor(x => x.Items[i].Name)
            @Html.DropDownListFor(x => x.Items[i].Name, Model.ItemsList, "Select...")
        </div>
    </div>
}

All other dropdowns on the page work, save the ones in loops such as above. What gives?


Answer

You need to set Selected manually for Model.ItemsList. You can't reuse the same list instance for each dropdown. No idea why MVC doesn't do this automatically.

@for (var i = 0; i < Model.Items.Count; i++)
{
    var options = Model.Items.Select(x => new SelectListItem { Text = x.Text, Value = x.Value, Selected = x.Value == Model.Items[i].Name });
    <div class="row">
        <div class="col-md-4">
            @Html.LabelFor(x => x.Items[i].Name)
            @Html.DropDownListFor(x => x.Items[i].Name, options, "Select...")
        </div>
    </div>
}