How do you localize enums for a ListBoxFor where multiple options are possible?
For example an enum that contains roles:
pu
I have used the accepted answer but changed it little bit. It is shorter and doesn't have custom class.
This is my enum. All items have DisplayAttribute
public enum OvertimeRequestedProvisionFor
{
[Display(ResourceType = typeof(Localization), Name = LocalizationKeys.General_Fee)]
Fee = 1,
[Display(ResourceType = typeof(Localization), Name = LocalizationKeys.General_Permit)]
Permit = 2,
}
And this is the extension method
public static string GetDisplayName(this Enum enumValue)
{
var fi = enumValue.GetType().GetField(enumValue.ToString());
var attributes = (DisplayAttribute[])fi.GetCustomAttributes(typeof(DisplayAttribute), false);
return attributes != null && attributes.Length > 0
? attributes[0].GetName()
: enumValue.ToString();
}
Now all have to do:
var localization = OvertimeRequestedProvisionFor.Fee.GetDisplayName();