Jsonresult display Displayname from an Enum

Asked

Viewed 585 times

0

I’m having a problem returning the Displayname of an Enum

I have the following Enum

public enum TipoPessoa
    {
        [Description("Pessoa Fisica")]
        [Display(Name = "Pessoa Fisica")]
        [JsonProperty("Pessoa Fisica")]
        Fisica = 0,

        [Display(Name = "Pessoa Juridica")]
        [Description("Pessoa Juridica")]
        [JsonProperty("Pessoa Juridica")]
        Juridica = 1
    }

and the following view model

public class EmpresaViewerViewModel
{
    public int Id { get; set; }

    [Display(Name = "Razão Social")]
    public string RazaoSocial { get; set; }

    [Display(Name = "Nome Fantasia")]
    public string NomeFantasia { get; set; }

    public int CNPJ { get; set; }

    [Display(Name = "Inscrição Estadual")]
    public int InscricaoEstadual { get; set; }

    [Display(Name = "Tipo de Pessoa")]
    public TipoPessoa TipoPessoa { get; set; }

    [Display(Name = "Código do Regime Tributário")]
    public CRT CRT { get; set; }

    public string Logradouro { get; set; }

    public string Complemento { get; set; }

    [DataType(DataType.PostalCode)]
    public string CEP { get; set; }

    public string Numero { get; set; }

    public string Bairro { get; set; }

    public string Cidade { get; set; }

    public string Estado { get; set; }

    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [DataType(DataType.PhoneNumber)]
    public string Telefone { get; set; }

    [DataType(DataType.PhoneNumber)]
    public string TelefoneCelular { get; set; }
}

and the following method in the controller

public JsonResult GetAll(string searchPhrase, int current = 1, int rowCount = 10)
    {
        // Ordenacao
        string columnKey = Request.Form.AllKeys.Where(k => k.StartsWith("sort")).First();
        string order = Request[columnKey];
        string field = columnKey.Replace("sort[", String.Empty).Replace("]", String.Empty);

        string fieldOrdened = String.Format("{0} {1}", field, order);

        List<PessoaEmpresa> pessoaEmpresa = repositoryEmpresa.Select();

        List<PessoaEmpresa> empresaPaginada = pessoaEmpresa.OrderBy(fieldOrdened).Skip((current - 1) * rowCount).Take(rowCount).ToList();

        List<EmpresaViewerViewModel> viewModel = AutoMapperManager.Instance.Mapper.Map<List<PessoaEmpresa>, List<EmpresaViewerViewModel>>(empresaPaginada);

        return  Json(new
        {
            rows = viewModel,
            current = current,
            rowCount = rowCount,
            total = pessoaEmpresa.Count()
        }, JsonRequestBehavior.AllowGet);
    }

But json returned the company type and crt comes as 0 or 1 and not the attribute name

2 answers

1

Try this, considering you’re using the library Newtonsoft.Json:

[JsonConverter(typeof(StringEnumConverter))] // Adicione isto
public enum TipoPessoa
{
   [Description("Pessoa Fisica")]
   [Display(Name = "Pessoa Fisica")]
   [JsonProperty("Pessoa Fisica")]
   [EnumMember(Value = "Pessoa Fisica")] // Adicione isto
   Fisica = 0,

   [Display(Name = "Pessoa Juridica")]
   [Description("Pessoa Juridica")]
   [JsonProperty("Pessoa Juridica")]
   [EnumMember(Value = "Pessoa Juridica")] // Adicione isto
   Juridica = 1
}

1


You can create a class to capture the custom attribute of the class property.

Here is an example of a custom class and below its usage

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

public static class EnumHelper<T>
{
    public static IList<T> GetValues(Enum value)
    {
        var enumValues = new List<T>();

        foreach (FieldInfo fi in value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public))
        {
            enumValues.Add((T)Enum.Parse(value.GetType(), fi.Name, false));
        }
        return enumValues;
    }

    public static T Parse(string value)
    {
        return (T)Enum.Parse(typeof(T), value, true);
    }

    public static IList<string> GetNames(Enum value)
    {
        return value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public).Select(fi => fi.Name).ToList();
    }

    public static IList<string> GetDisplayValues(Enum value)
    {
        return GetNames(value).Select(obj => GetDisplayValue(Parse(obj))).ToList();
    }

    private static string lookupResource(Type resourceManagerProvider, string resourceKey)
    {
        foreach (PropertyInfo staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
        {
            if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager))
            {
                System.Resources.ResourceManager resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null);
                return resourceManager.GetString(resourceKey);
            }
        }

        return resourceKey; // Fallback with the key name
    }

    public static string GetDisplayValue(T value)
    {
        var fieldInfo = value.GetType().GetField(value.ToString());

        var descriptionAttributes = fieldInfo.GetCustomAttributes(
            typeof(DisplayAttribute), false) as DisplayAttribute[];

        if (descriptionAttributes[0].ResourceType != null)
            return lookupResource(descriptionAttributes[0].ResourceType, descriptionAttributes[0].Name);

        if (descriptionAttributes == null) return string.Empty;
        return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();
    }
}

How to call the Enumhelper class in the view:

<ul>
    @foreach (var value in @EnumHelper<UserPromotion>.GetValues(UserPromotion.None))
    {
         if (value == Model.JobSeeker.Promotion)
        {
            var description = EnumHelper<UserPromotion>.GetDisplayValue(value);
            <li>@Html.DisplayFor(e => description )</li>
        }
    }
</ul>

In your View Model changes the Person Type property like this:

    TipoPessoa tipoPessoa;
        string tipoPessoa;
[Display(Name = "Tipo de Pessoa")]
        public string TipoPessoa {
            get {
                tipoPessoa = EnumHelper.<TipoPessoa>.GetDisplayValue(value);
                return tipoPessoa;
            }
            set {
                tipoPessoa = value;
            }
        }

Reference: Enum Helper

  • but how could I call in the json Return? List<Empresaviewerviewmodel> viewModel = Automappermanager.Instance.Mapper.Map<List<Personal Company>, List<Empresaviewerviewmodel>>(companyPaginada); Return Json(new { Rows = viewModel, Current = Current, rowCount = rowCount, total = personal Count() }, Jsonrequestbehavior.Allowget); }

  • you will use the display name with the correct Razor? @Html.Displayfor . If you will not use it this way, change the get in the view model that returns the value to pass through the Enumhelper.

  • no, I’m loading json into jquery bootgrid. @Alexandrecavaloti "get in the view model that returns the value to pass through the Enumhelper" how can I do this? can demonstrate an example

  • I included another snippet of code... the change in your viewmodel would look something like this...

  • I’ll test thank you

  • what I pass in <Type>

  • The Type of the Enum class

  • it says typePessoa = Enumhelper<Typopessoa>. Getdisplayvalue(value); value does not exist in the current context, and also what typePessoa already exists

Show 3 more comments

Browser other questions tagged

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