You cannot bind a <select>
element to a complex object (which is what Role
is) and when you submit the form, ModelState
is invalid (your trying to bind the selected Name
property of RolesList
to typeof IdentityRole
). You then return the view, but have not repopulated the RolesList
property, so its null
(hence the error).
View models should not contain data models, and you view model should be
public class RegisterViewModel
{
....
[Required(ErrorMessage = "Please select a role")]
public string Role { get; set; }
public IEnumerable<SelectListItem> RoleList { get; set; }
}
and in the GET method
var roles = _context.Roles.Select(r => r.Name);
var viewModel = new RegisterViewModel
{
RolesList = new SelectList(roles)
};
return View(viewModel);
and in the view
@Html.LabelFor(m => m.Role, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.Role, Model.RolesList, "Select Role", new { @class = "form-control" })
</div>
this will solve the invalid ModelState
issue relating to Role
, but if you do need to return the view because of other ModelState
issues, then you must first repopulate the collection before returning the view
if (!ModelState.IsValid)
{
var roles = _context.Roles.Select(r => r.Name);
model.RolesList = new SelectList(roles);
return View(model);
}
.... // save and redirect