Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC bug binding collection of DropDownList?

I have a view with 1 dropdown generated from Model property and 3 additional dropdowns that are generated from 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 AgentTypeListItems collection + sets default values for AgentType dropdown and 3 dropdowns 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 browser I get "2" everywhere though AgentTypes array was initialized with different values(!):

this is wrong

When I replace DropDownListFor with TextBoxFor:

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

I get the correct values in the inputs (!):

this is how it should be

It means the TextBoxFor works as expected, but DropDownListFor doesn't.

Is it 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; }
}
like image 202
Evgenyt Avatar asked Mar 25 '11 14:03

Evgenyt


2 Answers

I know that this post is more than a year old but it seems still to be a bug. Replacing

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

with

@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])
}

works for me.

like image 191
Aleksey Cherenkov Avatar answered Oct 25 '22 04:10

Aleksey Cherenkov


comment out your first line, @Html.DropDownListFor(m => m.AgentType, Model.AgentTypeListItems) what happens then?

Try this:

        @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]))
        }
like image 2
Adam Tuliper Avatar answered Oct 25 '22 04:10

Adam Tuliper