使用枚举作为 DropDownListFor 的数据源时的无效转换异常

Invalid cast exception where using Enum as data source to DropDownListFor

我正在我的控制器中将枚举转换为 IEnumerable<SelectListItem>,以便在 DropDownListFor 助手中使用它。

var roleList = EnumHelper.GetSelectList(typeof(UserRole))
           .Cast<UserRole>()
           .Except(new UserRole[] { UserRole.Admin, UserRole.Corporate })
           .Select(e => new SelectListItem { Text = e.ToString(), Value = ((int)e).ToString() });
ViewBag.SelectList = roleList;

我的剃刀代码看起来像

@Html.DropDownListFor(m => m.RoleID, (IEnumerable<SelectListItem>)ViewBag.SelectList)

但我遇到了错误

System.InvalidCastException: Specified cast is not valid.

为了确保它是一个有效的转换,我在控制器中检查了 roleList 的数据类型,它看起来很好,如下所示

在 运行 期间,我通过调试确保 ViewBag.SelectList 不为 null,并且没有任何问题

但是当我展开结果时我收到错误消息

EnumHelper.GetSelectList returns IList<SelectListItem> 然后 Cast<UserRole>() 抛出异常,因为它无法将 SelectListItem 转换为 UserRole。为了获得所有 enum 值,请使用 Enum.GetValues

var roleList = Enum.GetValues(typeof(UserRole))
       .Cast<UserRole>()
       .Except(new UserRole[] { UserRole.Admin, UserRole.Corporate })
       .Select(e => new SelectListItem { Text = e.ToString(), Value = ((int)e).ToString() });