ASP.NET MVC Binding DropDownList Collection Error?

I have a view with 1 drop-down list generated from the Model property, and three additional drop-down lists that are generated from the array property

@Html.DropDownListFor(m => m.AgentType, Model.AgentTypeListItems)
@for (int i = 0; i < Model.AgentTypes.Length; i++)
{
    @Html.DropDownListFor(m => m.AgentTypes[i], Model.AgentTypeListItems)
}

The controller method initializes Collection AgentTypeListItems + sets the default values ​​for the AgentType drop-down list and 3 drop-down lists for the collection:

var model = new OptionsViewModel();

// for DropDownListFor
model.AgentTypeListItems = new[]
{
    new SelectListItem { Text = "1", Value = "1" }, 
    new SelectListItem { Text = "2", Value = "2" },
    new SelectListItem { Text = "3", Value = "3" },
};

// 1 dropdown in the model
model.AgentType = "2";

// 3 dropdowns in array
model.AgentTypes = new[] { "3", "2", "1" };

return View(model);

When I open it in the browser, I get "2" everywhere, although the AgentTypes array is initialized with different values ​​(!):

this is wrong

When I replace DropDownListFor with TextBoxFor:

@Html.TextBoxFor(m => m.AgentTypes[i])

I get the correct values ​​on the inputs (!):

this is how it should be

This means that TextBoxFor works as expected, but DropDownListFor does not.

Is this a bug in MVC DropDownListFor?

UPDATE Here is the model class:

public class OptionsViewModel
{
    public SelectListItem[] AgentTypeListItems { get; set; }
    public string AgentType { get; set; }
    public string[] AgentTypes { get; set; }
}
+5
3

, , , , .

@Html.DropDownListFor(m => m.AgentType, Model.AgentTypeListItems)
@for (int i = 0; i < Model.AgentTypes.Length; i++)
{
    @Html.DropDownListFor(m => m.AgentTypes[i], Model.AgentTypeListItems)
}

@Html.DropDownListFor(m => m.AgentType, Model.AgentTypeListItems)
@for (int i = 0; i < Model.AgentTypes.Length; i++)
{
    @Html.DropDownListFor(m => m.AgentTypes[i], new SelectList(Model.AgentTypeListItems, "Value", "Text", Model.AgentTypes[i])
}

.

+14

, @Html.DropDownListFor(m = > m.AgentType, Model.AgentTypeListItems) ?

:

        @for (int i = 0; i < Model.AgentTypes.Length;  i++)
        {     
            string selected = Model.AgentTypes[i];
            @Html.DropDownListFor(m => selected, new SelectList(Model.AgentTypeListItems, "Text", "Value",Model.AgentTypes[i]))
        }
+2

I wonder if this is similar to the situation in WPF and Windows Forms, where using the same source element to select a list "binds" all the interface elements together behind the scenes? I remember that I had to create separate copies of the list object in these situations. It is worth a try.

0
source