You have to first create attribute for Enum which will be used on Enum fields for setting Display Name which will be user friendly :
public class EnumDisplayNameAttribute : Attribute
{
private string _displayName;
public string DisplayName
{
get { return _displayName; }
set { _displayName = value; }
}
}
and then you have to decorate attribute on your enum fields like this:
public enum EventType
{
[EnumDisplayName(DisplayName="Some User Friendly Name")]
Other = 0,
[EnumDisplayName(DisplayName="Some User Friendly Name")]
Birth = 1,
[EnumDisplayName(DisplayName="Some User Friendly Name")]
Marriage = 2,
[EnumDisplayName(DisplayName="Some User Friendly Name")]
Death = 3,
[EnumDisplayName(DisplayName="Some User Friendly Name")]
Brittish_Airways=4
}
and now add following extension method for Enum to your existing Extension Methods class or create a new one named EnumExtensions:
public static class ExtensionMethods
{
public static System.Web.Mvc.SelectList ToSelectList<TEnum>(this TEnum obj)
where TEnum : struct, IComparable, IFormattable, IConvertible // correct one
{
return new SelectList(Enum.GetValues(typeof(TEnum)).OfType<Enum>()
.Select(x =>
new SelectListItem
{
Text = x.DisplayName(),
Value = (Convert.ToInt32(x)).ToString()
}), "Value", "Text");
}
public static string DisplayName(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
EnumDisplayNameAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(EnumDisplayNameAttribute))
as EnumDisplayNameAttribute;
return attribute == null ? value.ToString() : attribute.DisplayName;
}
}
Now in your view use the extension method to return Enum fields as SelectList with User Friendly name as Text of options:
@using YourNamespace.ExtensionMethods;
@Html.DropDownListFor(model => model.EventTypeText,
EventType.Other.ToSelectList()),
new { @class = "ddlEventType ddl" })
you can also check my article (Binding Enum with DropdownList in asp.net mvc )