DropDownListFor not binding to value in a list of models

Viewed 39

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?

1 Answers

@Html.DropDownListFor works very weird way, when you init one, you have to init selected value too. So if you create list like this:

Users.Add(new UserModel { SelectedUserId = "2" }); 

you will have to assign selected item inside of UserModel :

 List<SelectListItem> users=null;

 public string SelectedUserId 
{ 

get {  return users.Where(u=>u.Selected).FirstOrDefault().Value;  }

set { 
       var  sUser=users.Where(u=>u.Value=value).FirstOrDefault();
       sUser.Selected=true;
 }

}

if you use net core much better to use " select " tag. It assigns automatically.

Related