Reputation: 4297
In my asp.net MVC5 projekt I'm making use of the [Display(Name="String")] annotation for Enums, which does work well as long as I'm using:
@Html.DisplayFor(modelItem => item.Category)
Now I'd like to use my pretty Enum names as link text in an
@Html.ActionLink(item.Category.ToString(), "Category", new { id = item.Category })
It of course works like this, but I dont see the DisplayName value (with spaces). How can I achieve this?
This is what my enums look like (just for clarification):
public enum Category
{
Book,
Movie,
[Display(Name = "TV Show")]
TVShow,
[Display(Name = "Video Game")]
Videogame,
Music,
Software,
Other
}
Upvotes: 0
Views: 720
Reputation: 1643
public static class EnumExtension
{
public static string GetDisplayName(this System.Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute), true);
if (attrs != null && attrs.Length > 0)
{
return ((DisplayAttribute)attrs[0]).Name;
}
}
return en.ToString();
}
}
and
@Html.ActionLink(item.Category.GetDisplayName(), "Category", new { id = item.Category })
Upvotes: 2