How to get the Display Name Attribute of an Enum member via MVC razor code?

后端 未结 20 2841
孤街浪徒
孤街浪徒 2020-11-22 09:30

I\'ve got a property in my model called \"Promotion\" that its type is a flag enum called \"UserPromotion\". Members of my enum have display attributes set as follows:

20条回答
  •  鱼传尺愫
    2020-11-22 09:44

    I have two solutions for this Question.

    1. The first solution is on getting display names from enum.
    public enum CourseLocationTypes
    {
        [Display(Name = "On Campus")]
        OnCampus,
        [Display(Name = "Online")]
        Online,
        [Display(Name = "Both")]
        Both
    }
    
    public static string DisplayName(this Enum value)
    {
        Type enumType = value.GetType();
        string enumValue = Enum.GetName(enumType, value);
        MemberInfo member = enumType.GetMember(enumValue)[0];
    
        object[] attrs = member.GetCustomAttributes(typeof(DisplayAttribute), false);
        string outString = ((DisplayAttribute)attrs[0]).Name;
    
        if (((DisplayAttribute)attrs[0]).ResourceType != null)
        {
            outString = ((DisplayAttribute)attrs[0]).GetName();
        }
    
        return outString;
    }
    

    @Model.CourseLocationType.DisplayName()

    1. The second Solution is on getting display name from enum name but that will be enum split in developer language it's called patch.
    public static string SplitOnCapitals(this string text)
    {
            var r = new Regex(@"
                (?<=[A-Z])(?=[A-Z][a-z]) |
                 (?<=[^A-Z])(?=[A-Z]) |
                 (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace);
    
            return r.Replace(text, " ");
    }
    
     
    @foreach (var item in Enum.GetNames(typeof(CourseLocationType))) { } @Html.ValidationMessageFor(x => x.CourseLocationType)

提交回复
热议问题