Ad

Display A Custom Text For Enum Dropdown List In MVC

- 1 answer

I'm unable to display custom text for enum. When I try to display I get Slot1, Slot2, etc.

What do I do to get the custom text?

public enum TimeSlots
{
    [Display(Name [email protected]"11:00AM - 12:00PM")]
    Slot1,
    [Display(Name = @"12:00PM - 10:00PM")]
    Slot2,
    [Display(Name [email protected]"01:00PM - 02:00PM")]
    Slot3,
    [Display(Name = "02:00PM - 03:00PM")]
    Slot4,
    [Display(Name = "03:00PM - 04:00PM")]
    Slot5,
    [Display(Name = "04:00PM - 05:00PM")]
    Slot6
}

Following is the code for the DropDownList:

    <label asp-for="TimeSlot"></label>
    @Html.DropDownListFor(m => m.TimeSlot,
        new SelectList(Enum.GetValues(typeof(TimeSlots))),"Select TimeSlot",new { @class = "form-control" })                 
Ad

Answer

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

Ad
source: stackoverflow.com
Ad