I have the following two models, one of which contains a list of the other model i.e. UserModels.
public class UserModel
{
public int SelectedUserId { get; set; }
public SelectList UserOptions { get; set; }
public UserModel()
{
var users = new List<SelectListItem>
{
new SelectListItem { Text = "Mickey Mouse", Value = "1" },
new SelectListItem { Text = "Goofy", Value = "2" },
new SelectListItem { Text = "Donald Duck", Value = "3" },
};
UserOptions = new SelectList(users, "Value", "Text");
}
}
public class MyModel
{
public IList<UserModel> Users { get; set; }
public MyModel()
{
Users = new List<UserModel>();
}
}
When I attempt to bind this list of UserModels to a MVC Razor page with multiple DropDownList, the values do not bind and the selected item in the DropDownList is not displayed correctly.
@for(int i=0; i < Model.Users.Count; i++)
{
@Html.DropDownListFor(x => x.Users[i].SelectedUserId, Model.Users[i].UserOptions)
}
However, if I select different values in each DropDownList on the page and then post the form back to the server, the correct values bind within each individual UserModel in the List of models i.e. 'Users'.
Am I missing something here? Is this a known bug? Why is it when setting the values of SelectedUserId in each model on the server, does the correct option in the select list not bind, but selecting an option in the select list on the web page does work?