0

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

cast error

during run time I ensured that ViewBag.SelectList is not null by debugging and there is no issues

Debug mode

but when I expand the result I get error message

error finally

3
  • Well, I guess when you tried to cast enum as int in (int)e there's the problem raised. I believe you are trying to cast abc as int there. Parse it as string and re-run Commented Oct 2, 2019 at 5:02
  • @Shahjahan Thanks for the comment. I tried and it still doesn't work. (int)Enum.Member gives integer value from enum. Commented Oct 2, 2019 at 5:23
  • have you tried: @Html.DropDownListFor(m => m.RoleID, ViewBag.SelectList)? Commented Oct 2, 2019 at 6:27

1 Answer 1

1

EnumHelper.GetSelectList returns IList<SelectListItem> and then Cast<UserRole>() throws an exception because it cannot cast SelectListItem to UserRole. In order to get all enum values use 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() });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.