Send Display Text of an Enum by Json

2

Well, I have an enum for the days of the week, being:

    Segunda = 2,
    [Display(Name="Terça")]
    Terca = 3,
    Quarta = 4,
    Quinta = 5,
    Sexta = 6,
    [Display(Name = "Sábado")]
    Sabado = 7
So I build an object that has a day of the week in Api , and I do a get json in javascript and show it on the screen using knockout , the problem is that if I leave it as an enum, it will show the number equivalent to the day, and if I do ToString() it shows the normal name, no accents and no special characters, what I would like to display was the display, is there any method that does this? or do I have to do "on hand"?

    
asked by anonymous 19.01.2016 / 20:50

2 answers

0

I made a code that returns the text of [Display(Name = "texto"] , for those who need to return it to the screen by javascript or some other way.

        public static string GetDisplayNameEnum(Enum enumValue)
        {
           var displayName = enumValue.GetType().GetMember(enumValue.ToString())
                       .First()
                       .GetCustomAttribute<DisplayAttribute>()?
                       .Name;

           return displayName ?? enumValue.ToString();
        }
    
23.05.2016 / 19:20
0

Another option, using extension method and the Description attribute would be:

Enum:

public enum Status
{
    [Description("Aguardando Aprovação")]       
    AguardandoAprovacao = 0,

    Aprovado = 1,       
    Recusado = 2        
}

Extension class and method:

public static class EnumExtensions
{
    public static string DisplayDescription(this Enum value)
    {
        if (value == null)
            return null;

        FieldInfo field = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }
}

Using:

string textoEnum = Status.AguardandoAprovacao.DisplayDescription()

I left the .NETFiddle for reference

    
05.06.2018 / 02:26