Last active
March 8, 2020 11:01
-
-
Save ermirbeqiraj/fb194fef62ddcbff242569a85196dd3b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class EnumHelper | |
{ | |
public static string Description(this Enum value) | |
{ | |
FieldInfo fi = value.GetType().GetField(value.ToString()); | |
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); | |
return attributes.Length > 0 ? attributes[0].Description : value.ToString(); | |
} | |
public static List<EnumDrop<T>> EnumerateDrop<T>() where T : Enum | |
{ | |
var values = new List<EnumDrop<T>>(); | |
foreach (var item in Enum.GetValues(typeof(T))) | |
{ | |
values.Add(new EnumDrop<T> { Key = (T)item }); | |
} | |
return values; | |
} | |
} | |
public class EnumDrop<T> where T : Enum | |
{ | |
public T Key { get; set; } | |
public string Value => Key.Description(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample enum:
Mvc dropdown list:
In
_ViewImports.cshtml
add@using static <NAMESPACE_OF_HELPERS>.EnumHelper
In mvc view file get enum text: