Display a custom text for enum dropdown list in MVC

Try the following:

@Html.DropDownList("enumlist1", Enum.GetValues(typeof(TimeSlots))
    .Cast<TimeSlots>()
    .Select(e => new SelectListItem() { Value = e.ToString(), Text = e.GetDisplayName() }))

The code above uses the following extension method:

public static class EnumExtensions
{
    public static string GetDisplayName(this Enum value)
    {
        return value.GetType()
          .GetMember(value.ToString())
          .First()
          .GetCustomAttribute<DisplayAttribute>()
          ?.GetName();
    }
}

The created drop-down list looks like below:

enter image description here

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top