0

I try to convert Enum to SelectListItem. I can get the text but I can't get the value itself.

here is my attempt.

      // A method to convert Enum to SelectListItem
      public static IEnumerable<SelectListItem> GetEnumSelectList<T>()
      {
          return (Enum.GetValues(typeof(T)).Cast<T>().Select(
            enu => new SelectListItem() { Text = enu.ToString(), Value = enu.ToString() })).ToList();
      }

this method returns Text = enu.ToString(), Value = enu.ToString()

returning Text is fine but it is the same with Value.

I don't know how to retrieve values of the enum so I can get 0,1 instead of Import or Export

1
  • Cast it to an int Commented Jul 22, 2020 at 20:37

1 Answer 1

0

Assuming you didn't change your underlying enum type (default is int), you can just cast it:

new SelectListItem() { Text = enu.ToString(), Value = (int) enu }

If you changed the underlying type (e.g. to Guid), of course make sure to cast it to the appropriate type.

Sign up to request clarification or add additional context in comments.

Comments