Here's a simplified (and working) version of akousmata's localized enum extension:
public static string DisplayName(this Enum enumValue)
{
var enumType = enumValue.GetType();
var memberInfo = enumType.GetMember(enumValue.ToString()).First();
if (memberInfo == null || !memberInfo.CustomAttributes.Any()) return enumValue.ToString();
var displayAttribute = memberInfo.GetCustomAttribute<DisplayAttribute>();
if (displayAttribute == null) return enumValue.ToString();
if (displayAttribute.ResourceType != null && displayAttribute.Name != null)
{
var manager = new ResourceManager(displayAttribute.ResourceType);
return manager.GetString(displayAttribute.Name);
}
return displayAttribute.Name ?? enumValue.ToString();
}
Note: I move enumType
from a parameter to a local variable.
Example usage:
public enum IndexGroupBy
{
[Display(Name = "By Alpha")]
ByAlpha,
[Display(Name = "By Type")]
ByType
}
And
@IndexGroupBy.ByAlpha.DisplayName()
Here is a editor template that can be used with the extension method above:
@model Enum
@{
var listItems = Enum.GetValues(Model.GetType()).OfType<Enum>().Select(e =>
new SelectListItem
{
Text = e.DisplayName(),
Value = e.ToString(),
Selected = e.Equals(Model)
});
var prefix = ViewData.TemplateInfo.HtmlFieldPrefix;
var index = 0;
ViewData.TemplateInfo.HtmlFieldPrefix = string.Empty;
foreach (var li in listItems)
{
var fieldName = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", prefix, index++);
<div class="editor-radio">
@Html.RadioButton(prefix, li.Value, li.Selected, new {@id = fieldName})
@Html.Label(fieldName, li.Text)
</div>
}
ViewData.TemplateInfo.HtmlFieldPrefix = prefix;
}
And here is an example usage:
@Html.EditorFor(m => m.YourEnumMember, "Enum_RadioButtonList")