1

I want to create a dropdown list using description of enum instead of its value.

I'd like to know how to get descriptions instead of values in the following code which creates a dropdown list for enum :

    public static MvcHtmlString DropDownListForEnum<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
    {
        // get expression property description
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

        IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();

        IEnumerable<SelectListItem> items =
            values.Select(value => new SelectListItem
            {
                Text = value.ToString(),
                Value = value.ToString(),
                Selected = value.Equals(metadata.Model)
            });

        return htmlHelper.DropDownListFor(
            expression,
            items
            );
    }
user3391714
  • 57
  • 1
  • 6
  • possible duplicate of [How to get string list of Enum descriptions?](http://stackoverflow.com/questions/13059036/how-to-get-string-list-of-enum-descriptions) – Mario Stoilov Mar 07 '14 at 09:41

2 Answers2

1

First, make a new method to get the description like shown below:

public static string GetDescription<T>(string value)
        {
            Type type = typeof(T);
            if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                type = Nullable.GetUnderlyingType(type);
            }

            T enumerator = (T)Enum.Parse(type, value);

            FieldInfo fi = enumerator.GetType().GetField(enumerator.ToString());

            DescriptionAttribute[] attributtes =
                (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributtes != null && attributtes.Length > 0)
                return attributtes[0].Description;
            else
                return enumerator.ToString();
        }

And then use it in your helper:

    public static MvcHtmlString DropDownListForEnum<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
{
    // get expression property description
    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

    IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();

    IEnumerable<SelectListItem> items =
        values.Select(value => new SelectListItem
        {
            Text = value.ToString(),
            Value = GetDescription<TEnum>(value.ToString()),
            Selected = value.Equals(metadata.Model)
        });

    return htmlHelper.DropDownListFor(
        expression,
        items
        );
}
frikinside
  • 1,244
  • 1
  • 9
  • 19
0

Use Enum getnames to get the names

http://msdn.microsoft.com/en-us/library/system.enum.getnames(v=vs.110).aspx

gericooper
  • 242
  • 2
  • 11