Skip to content

Instantly share code, notes, and snippets.

@kamranayub
Created October 14, 2011 16:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamranayub/1287511 to your computer and use it in GitHub Desktop.
Save kamranayub/1287511 to your computer and use it in GitHub Desktop.
Drop-down for Enum MVC helper
public static MvcHtmlString DropdownForEnum<TModel>(this HtmlHelper<TModel> helper, Type type,
string name, string optionLabel, object htmlAttributes)
{
if (!type.IsEnum) throw new ArgumentException("type must be that of an enum", "type");
var dictionary = new Dictionary<string, string>();
var values = type.GetEnumValues();
foreach (var val in values)
{
dictionary.Add(
val.ToString(),
type.GetDescriptionForEnum(val)
);
}
return helper.DropDownList(name, dictionary.ToSelectList(string.Empty), optionLabel, htmlAttributes);
}
public static SelectList ToSelectList(this IDictionary<string, string> dictionary, object selectedValue)
{
return new SelectList(dictionary, "Key", "Value", selectedValue);
}
/// <summary>
/// Gets the DescriptionAttribute valud of an enum value, if none are found uses the string version of the specified value
/// </summary>
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
return GetEnumDescription(value.ToString(), type);
}
public static string GetDescriptionForEnum(this Type type, object value)
{
return GetEnumDescription(value.ToString(), type);
}
private static string GetEnumDescription(string value, Type type)
{
MemberInfo[] memberInfo = type.GetMember(value);
if (memberInfo != null && memberInfo.Length > 0)
{
// default to the first member info, it's for the specific enum value
var info = memberInfo.First().GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault();
if (info != null)
return ((DescriptionAttribute)info).Description;
}
// no description - return the string value of the enum
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment