I am converting enum to IEnumerable<SelectListItem> in my controller in order to use it in DropDownListFor helper.
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;
and my razor code looks like
@Html.DropDownListFor(m => m.RoleID, (IEnumerable<SelectListItem>)ViewBag.SelectList)
but I am getting an error
System.InvalidCastException: Specified cast is not valid.
To make sure it is a valid cast I checked datatype of roleList in controller and it looks fine as shown below
during run time I ensured that ViewBag.SelectList is not null by debugging and there is no issues
but when I expand the result I get error message



(int)ethere's the problem raised. I believe you are trying to castabcasintthere. Parse it as string and re-run@Html.DropDownListFor(m => m.RoleID, ViewBag.SelectList)?