rajeemcariazo
rajeemcariazo

Reputation: 2524

Display name of enum dropdownlist in Razor

How can I display the custom names of my enums in dropdownlist in Razor? My current code is:

@Html.DropDownListFor(model => model.ExpiryStage,
        new SelectList(Enum.GetValues(typeof(ExpiryStages))),
        new { @class = "selectpicker" })

My enum is:

public enum ExpiryStages
{
    [Display(Name = "None")]
    None = 0,

    [Display(Name = "Expires on")]
    ExpiresOn = 1,

    [Display(Name = "Expires between")]
    ExpiresBetween = 2,

    [Display(Name = "Expires after")]
    ExpiresAfter = 3,

    [Display(Name = "Current")]
    Current = 4,

    [Display(Name = "Expired not yet replaced")]
    ExpiredNotYetReplaced = 5,

    [Display(Name = "Replaced")]
    Replaced = 6
}

For example, I want to display "Expired not yet replaced" instead of ExpiredNotYetReplaced in my DropDownList.

Upvotes: 24

Views: 25613

Answers (4)

Zubayer Bin Ayub
Zubayer Bin Ayub

Reputation: 310

you can use for dropdown asp.net core

                    <select asp-for="DeliveryPolicy" asp-items="Html.GetEnumSelectList<ExpiryStages>()">
                        <option selected="selected" value="">Please select</option>
                    </select>

Upvotes: 3

bergmeister
bergmeister

Reputation: 969

In ASP.Net Core, one can use the HtmlHelper method IHtmlHelper.GetEnumSelectList(), which can be used as follows for example:

asp-items="@Html.GetEnumSelectList<MyEnumType>()"

Upvotes: 3

Muhammad Waqas Iqbal
Muhammad Waqas Iqbal

Reputation: 3344

From MVC 5.1, they have added this new helper. You just need an enum

public enum WelcomeMessageType
    {
        [Display(Name = "Prior to accepting Quote")]
        PriorToAcceptingQuote,
        [Display(Name = "After Accepting Quote")]
        AfterAcceptingQuote
    }

and you can create the dropdownlist showing the names by writing

@Html.EnumDropDownListFor(model => model.WelcomeMessageType, null, new { @id = "ddlMessageType", @class = "form-control", @style = "width:200px;" })

Upvotes: 40

James Hull
James Hull

Reputation: 3689

I have a enum extension to retrieve the display name.

public static string GetDescription<TEnum>(this TEnum value)
{
    var attributes = value.GetAttributes<DescriptionAttribute>();
    if (attributes.Length == 0)
    {
       return Enum.GetName(typeof(TEnum), value);
    }

    return attributes[0].Description;
}

Which you can use like this:

Enum.GetValues(typeof(ExpiryStages)).Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });

I use a handy helper to generate select lists from enums:

public static SelectList SelectListFor<T>() 
        where T : struct
{
    var t = typeof (T);

    if(!t.IsEnum)
    {
        return null;
    }

    var values = Enum.GetValues(typeof(T)).Cast<T>()
                   .Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });

    return new SelectList(values, "Id", "Name");
}

Upvotes: 6

Related Questions