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

后端 未结 20 2369
孤街浪徒
孤街浪徒 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:47

    2020 Update: An updated version of the function provided by many in this thread but now for C# 7.3 onwards:

    Now you can restrict generic methods to enums types so you can write a single method extension to use it with all your enums like this:

    The generic extension method:

    public static string ATexto(this T enumeración) where T : struct, Enum {
        var tipo = enumeración.GetType();
        return tipo.GetMember(enumeración.ToString())
        .Where(x => x.MemberType == MemberTypes.Field && ((FieldInfo)x).FieldType == tipo).First()
        .GetCustomAttribute()?.Name ?? enumeración.ToString();
    } 
    

    The enum:

    public enum TipoImpuesto { 
    IVA, INC, [Display(Name = "IVA e INC")]IVAeINC, [Display(Name = "No aplica")]NoAplica };
    

    How to use it:

    var tipoImpuesto = TipoImpuesto.IVAeINC;
    var textoTipoImpuesto = tipoImpuesto.ATexto(); // Prints "IVA e INC".
    

    Bonus, Enums with Flags: If you are dealing with normal enums the function above is enough, but if any of your enums can take multiple values with the use of flags then you will need to modify it like this (This code uses C#8 features):

        public static string ATexto(this T enumeración) where T : struct, Enum {
    
            var tipo = enumeración.GetType();
            var textoDirecto = enumeración.ToString();
    
            string obtenerTexto(string textoDirecto) => tipo.GetMember(textoDirecto)
                .Where(x => x.MemberType == MemberTypes.Field && ((FieldInfo)x).FieldType == tipo)
                .First().GetCustomAttribute()?.Name ?? textoDirecto;
    
            if (textoDirecto.Contains(", ")) {
    
                var texto = new StringBuilder();
                foreach (var textoDirectoAux in textoDirecto.Split(", ")) {
                    texto.Append($"{obtenerTexto(textoDirectoAux)}, ");
                }
                return texto.ToString()[0..^2];
    
            } else {
                return obtenerTexto(textoDirecto);
            }
    
        } 
    

    The enum with flags:

    [Flags] public enum TipoContribuyente {
        [Display(Name = "Común")] Común = 1, 
        [Display(Name = "Gran Contribuyente")] GranContribuyente = 2, 
        Autorretenedor = 4, 
        [Display(Name = "Retenedor de IVA")] RetenedorIVA = 8, 
        [Display(Name = "Régimen Simple")] RégimenSimple = 16 } 
    

    How to use it:

    var tipoContribuyente = TipoContribuyente.RetenedorIVA | TipoContribuyente.GranContribuyente;
    var textoAux = tipoContribuyente.ATexto(); // Prints "Gran Contribuyente, Retenedor de IVA".
    

提交回复
热议问题