Search code examples
c#asp.netrazorenumsrazor-pages

How to get items of enum in c#?


I want to create a select option in Razor pages from Enum object Description

This is my code:

<div class="dropdown-box">
    <select id="type-select">
        @foreach (var item in Enums.OrderStatus)
        {
            <option>@item</option>
        }
    </select>
</div>

and the enum:

public enum OrderStatus
{
    [Description("در انتظار تایید")]
    PendingForAccept = 0,

    [Description("تمام شده")]
    Finished = 1,

    [Description("لغو شده")]
    Canceled = 2,

    [Description("رد شده")]
    Rejected = 3,

    [Description("تایید شده")]
    Accepted = 4
}

How can I extract items descriptions of this enum to string


Solution

  • Here's an example of code that does it.

    public static string ExtractDescription<T>(T enumVal) where T : struct
    {
        var type = enumVal.GetType();
        if (!type.IsEnum)
        {
            throw new ArgumentException($"{nameof(enumVal)} must be an Enum", nameof(enumVal));
        }
    
        var memberInfo = type.GetMember(enumVal.ToString());
        if (memberInfo.Length > 0)
        {
            var attributes = memberInfo[0].GetCustomAttributes(attributeType: typeof(DescriptionAttribute), inherit: false);
    
            if (attributes.Length > 0)
            {
                return ((DescriptionAttribute)attributes[0]).Description;
            }
        }
    
        return enumVal.ToString();
    }
    

    Usage:

    var s = ExtractDescription(OrderStatus.PendingForAccept)// s is "در انتظار تایید"