Value cannot be null. Parameter name: items (in Dropdown List) ASP.NET MVC5

后端 未结 5 465
终归单人心
终归单人心 2020-12-02 00:18

I have problem in my code. I\'m using the registration form which comes with MVC5 , I added a field \"Role\" as a Dropdownlist to assign a role to the user while creating a

5条回答
  •  情话喂你
    2020-12-02 01:02

    Personally I would create the select list in your controller and pass it to the model, writing something like

      var RolesList = new List
                {
                    new SelectListItem { Value = string.Empty, Text = "Please select a Role..." }
                };
    
       RolesList.AddRange(roles.Select(t => new SelectListItem
                {
                    Text = t.role,
                    Value = t.Id.ToString()
                }));` 
    

    and then add this to your model, in your model you can then use

    @Html.DropDownListFor(m => m.Role, Model.RoleList, new { @class = "form-control" })
    

    This method/syntax works for me I am not sure if It is 'best practice' though

提交回复
热议问题