Skip to content

Instantly share code, notes, and snippets.

@ermirbeqiraj
Last active March 8, 2020 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ermirbeqiraj/fb194fef62ddcbff242569a85196dd3b to your computer and use it in GitHub Desktop.
Save ermirbeqiraj/fb194fef62ddcbff242569a85196dd3b to your computer and use it in GitHub Desktop.
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();
}
@ermirbeqiraj
Copy link
Author

ermirbeqiraj commented Mar 8, 2020

Sample enum:

    public enum Countries
    {
        Australia = 0,
        [Description("United Kingdom")]
        UnitedKingdom = 1,
        [Description("United States")]
        UnitedStates = 2,
        [Description("New Zeland")]
        NewZeland = 3
    }

Mvc dropdown list:

ViewBag.Regions = new SelectList(EnumHelper.EnumerateDrop<Countries>(), "Key", "Value");

In _ViewImports.cshtml add @using static <NAMESPACE_OF_HELPERS>.EnumHelper
In mvc view file get enum text:

@model.Country.Description()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment