random techno tidbits
ASP.NET MVC bug binding collection of DropDownList?
Recently, while experimenting with strongly-typed form helpers of MVC, I found a bug.
I posted a question at SO, but with no luck so far.
Generally, looks like DropDownFor is broken when trying to bind collection of form drop downs.
I have a workaround in form of using non-typed helper, but anyway hope to get things sorted out with strongly-typed one.
So. The bug.
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);
The model class:
public class OptionsViewModel { public SelectListItem[] AgentTypeListItems { get; set; } public string AgentType { get; set; } public string[] AgentTypes { get; set; } }
When I open it in browser I get “2″ everywhere though AgentTypes array was initialized with different values(!):

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.
Will try to post the issue into MVC project bugtracker.