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?
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
}
}