how to use enum with DescriptionAttribute in asp.net mvc

前端 未结 4 1453
故里飘歌
故里飘歌 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:22

    The Html helper EnumDropDownListFor or EnumDropDownList does not take into consideration the Description attribute decorations on the enum members. However by reviewing the source code:

    Enum Dropdown List Helper: https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/SelectExtensions.cs

    Enum Helper Classes: https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/EnumHelper.cs

    The enum helper classes above are used to convert an Enum to a List. From the code below:

    // Return non-empty name specified in a [Display] attribute for the given field, if any; field's name otherwise
    private static string GetDisplayName(FieldInfo field)
    {
        DisplayAttribute display = field.GetCustomAttribute(inherit: false);
        if (display != null)
        {
            string name = display.GetName();
            if (!String.IsNullOrEmpty(name))
            {
                return name;
            }
        }
    
        return field.Name;
    }
    

    You can see that in the method GetDisplayName it checks for the existence of the DisplayAttribute on the enum member. If the display attribute exists then the name is set to the result of DisplayAttribute.GetName() method.

    Putting this together we can modify the enum to use the DisplayAttribute instead of the DescriptionAttribute and setting the Name property to the value you wish to display.

    public enum SearchBy
    {
        [Display(Name = "SID/PID")]
        SID = 1,
        [Display(Name = "Name")]
        Name,
        [Display(Name = "Birth Date")]
        DOB,
        [Display(Name = "Cause#")]
        Cause
    }
    

    This gives you the result you wish.

    enter image description here

    Hope this helps.

提交回复
热议问题