Skip to content

Instantly share code, notes, and snippets.

@geocine
Last active March 16, 2019 04:41
Show Gist options
  • Save geocine/6145778 to your computer and use it in GitHub Desktop.
Save geocine/6145778 to your computer and use it in GitHub Desktop.
EnumDropDownList and EnumHelpers
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace Geocine.Helpers
{
public static class EnumHelpers
{
public static HtmlString EnumDropDownList<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(
//Convert.ToInt32(val).ToString(),
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;
}
public static T GetValueFromDescription<T>(string description)
{
var type = typeof(T);
if (!type.IsEnum) throw new InvalidOperationException();
foreach (var field in type.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attribute != null)
{
if (attribute.Description == description)
return (T)field.GetValue(null);
}
else
{
if (field.Name == description)
return (T)field.GetValue(null);
}
}
throw new ArgumentException("Not found.", "description");
// or return default(T);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment