简体   繁体   English

DropDownListFor报告类型不匹配

[英]DropDownListFor reports type mismatch

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> 加载用于创建新用户的页面时,出现异常,指出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"}
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM