Model:
[Required(ErrorMessage = "You must assign this user a role")]
[Display(Name = "Role")]
public string UserRole { get; set; }
public IEnumerable<System.Web.Mvc.SelectListItem> UserRoles { get; set; }
Controller:
public ActionResult CreateNewUser()
{
CreateNewUserModel model = new CreateNewUserModel();
model.UserRoles = new []
{
new SelectListItem{Value="Administrator", Text="Administrator"},
new SelectListItem{Value="User", Text="User"}
};
//model.UserRole = "Administrator";
return View(model);
}
View:
@Html.DropDownListFor(x => x.UserRole, Model.UserRoles,"Select a role")
@Html.ValidationMessageFor(x=>x.UserRole)
When the page to create a new user is loaded, I have got an exception stating that UserRole must be of type IEnumerable<SelectList>
Try changing:
model.UserRoles = new []
{
new SelectListItem{Value="Administrator", Text="Administrator"},
new SelectListItem{Value="User", Text="User"}
};
to:
model.UserRoles = List<SelectListItem>
{
new SelectListItem{Value="Administrator", Text="Administrator"},
new SelectListItem{Value="User", Text="User"}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.