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(!):
When I replace DropDownListFor with TextBoxFor:
@Html.TextBoxFor(m => m.AgentTypes[i])
I get the correct values in the inputs (!):
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; }
}
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.
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])) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With