DropDownListFor报告类型不匹配

本文关键字:不匹配 类型 报告 DropDownListFor | 更新日期: 2023-09-27 17:59:10

型号:

    [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; }

控制器:

    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);
    }

视图:

    @Html.DropDownListFor(x => x.UserRole, Model.UserRoles,"Select a role")
    @Html.ValidationMessageFor(x=>x.UserRole)

当加载创建新用户的页面时,我得到一个异常,说明UserRole must be of type IEnumerable<SelectList>

DropDownListFor报告类型不匹配

尝试更改:

model.UserRoles = new []
    {
        new SelectListItem{Value="Administrator", Text="Administrator"},
        new SelectListItem{Value="User", Text="User"}
    };

至:

model.UserRoles = List<SelectListItem>
    {
        new SelectListItem{Value="Administrator", Text="Administrator"},
        new SelectListItem{Value="User", Text="User"}
    };