Sending Text from an Enum display by Json

Asked

Viewed 347 times

2

Guys, I’ve got an Enum for 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 on Api, and I do a get json in javascript and show on screen using knockout, the problem is that if I leave as 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 show was the display, is there any method that does this? or I have to do "in hand"?

  • give a look and see if it helps you http://stackoverflow.com/questions/25248521/bind-an-enum-to-a-combo-box-using-knockout

  • thanks, but he has a different problem...

  • then friend please demonstrate the error in order to help .... we also need something you have already done to make it easier

2 answers

1

Another option, using extension method and the attribute Description 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 in the .Netfiddle for reference

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 in some other way.

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

           return displayName ?? enumValue.ToString();
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.