Display Name with Razor

Asked

Viewed 294 times

1

I have this case in my project?

public enum TipoValorCalculoComissao
{
    [Display(Name = "Percentual")]
    Percentual = 1,
    [Display(Name = "Valor")]
    Valor = 2
}

And I would like to put these values in a combo, but applying Name instead of the Enum description. But the only way I could do that was to create a class that way:

public class TipoValorCalculoComissaoView
{
    public int Valor { get; set; }

    public string Nome { get; set; }
}

And call it that:

private void ObterTipoValorCalculoComissao()
    {
        ViewBag.TipoValorCalculoComissao = Enum.GetValues(typeof(TipoValorCalculoComissao)).Cast<TipoValorCalculoComissao>()
                                                               .Select(v => new TipoValorCalculoComissaoView
                                                               {
                                                                   Nome = v.ToString(),
                                                                   Valor = (int)v
                                                               }).ToList();
    }

However this way I do not catch the Name of the object, someone knows some way to catch the Name of the object for display via Razor.

1 answer

1


Try something like that:

public static string GetDescription(this System.Enum en)
{
    Type type = en.GetType();

    MemberInfo[] memberInfo = type.GetMember(en.ToString());

    if (memberInfo != null && memberInfo.Length > 0)
    {
        var attrs = memberInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);

        if (attrs != null && attrs.Length > 0)
        {
            return ((DisplayAttribute)attrs[0]).Name;
        }
    }

    return en.ToString();
}
  • Good morning Rodolpho I did a similar function and ended up working, but the question is... Name is already a Dataannotations, if I pass everything to the view, because Razor can not get this attribute of the object in a simpler way...

  • Because when you are calling Tostring(), it is calling the method that comes from the Object class, which usually shows the type class name. That’s why you need to say explicitly that you want to read the property name of the attribute in question. Also, the same object can contain several related attributes.

Browser other questions tagged

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