How to get Display Text from EnumDropDownListFor on post?

1.4k views Asked by At

Is there a way to get DisplayName (Text) from EnumDropDownListFor helper for enum?

Enum:

public enum PartnersGroup
{
   [Display(Name="Partner_SystemsGroup",ResourceType=typeof(Global) )]
    SystemsGroup,
   [Display(Name="Partner_SoftwarePartners",ResourceType=typeof(Global))]
    SoftwarePartners,
   [Display(Name="Partner_IntegrationPartners",ResourceType=typeof(Global))]
    IntegrationPartners,

}

Model

public class Partner
{
    public PartnersGroup PartnersGroup { get; set; }
}

Controller

// GET: Partners/Create
public ActionResult Create()
{
    ----
    return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Partner partner)
{
    if (ModelState.IsValid)
    {
        // here model does not show language based text(shown in dropdown in view). Getting Enum value like "IntegrationPartners".
        // In model parner.ParnerGroup shows IntegrationPartners, but it should be "Integration Partners" in English or "Partenaires d'intégration" in French.
         // Save to DB
    }        
}

View (Create) is displaying language based resource values as expected for keys. It is working fine.

 @Html.EnumDropDownListFor(model => model.PartnersGroup)

Any help please?

2

There are 2 answers

1
alisabzevari On BEST ANSWER

You can write an extension method for Enums to return Display value of an Enum value:

public static class DataAnnotationHelpers
{
    public static string GetDisplayValue(this Enum instance)
    {
        var fieldInfo = instance.GetType().GetMember(instance.ToString()).Single();
        var descriptionAttributes = fieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false) as DisplayAttribute[];
        if (descriptionAttributes == null) return instance.ToString();
        return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].GetName() : instance.ToString();

    }

}

And Use it like this:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Partner partner)
{
    if (ModelState.IsValid)
    {
         var localizedDisplayName = partner.PartnersGroup.GetDisplayValue();
         // Save to DB
    }        
}
0
Bellash On

Approximate solution is add PartnersGroupString property getter in the partner class in order to transform enum into their localized strings. See bellow code

public class Partner
{
   public PartnersGroup PartnersGroup { get; set; }

   [doNotGenerateIntoDatabase]
   public string PartnersGroupString { 
  get{ 
        return  
               Strings.ResourceManager.GetString("PartnersGroup_" + this.PartnersGroup);}
   }

}

then you can use this property in your controller using ...model.PartnersGroupString