DropDownListFor报告类型不匹配

时间:2013-02-14 21:52:55

标签: c# asp.net asp.net-mvc

型号:

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

1 个答案:

答案 0 :(得分:0)

尝试更改:

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