how to use enum with DescriptionAttribute in asp.net mvc

前端 未结 4 1456
故里飘歌
故里飘歌 2021-02-07 06:02

I am new to asp.net MVC. I am trying to use dropdown control on my view page, which populates from enum. I also want to add custom descriptions to dropdown values. I searched so

4条回答
  •  走了就别回头了
    2021-02-07 06:23

    Given :

    public enum MyEnum
    {
        [Description("This is the description if my member A")]
        A,
        [Description("This is the description if my member B")]
        B
    }
    

    I personally use this extension method to get a description from my enum:

     public static string GetDescription(this Enum value)
            {
                FieldInfo fi = value.GetType().GetField(value.ToString());
    
                DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
    
                if (attributes != null && attributes.Length > 0)
                {
                    return attributes[0].Description;
                }
                else
                {
                    return value.ToString();
                }
            }
    

    To use it:

    MyEnum.A.GetDescription();
    

    Hope this help.

提交回复
热议问题