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
You cannot bind a 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 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" })
@Html.DropDownListFor(m => m.Role, Model.RolesList, "Select Role", new { @class = "form-control" })
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