使用描述C#创建枚举的下拉列表

时间:2014-03-07 09:35:31

标签: c# enums html.dropdownlistfor

我想使用枚举的描述而不是其值来创建下拉列表。

我想知道如何在以下代码中获取描述而不是值,这会为枚举创建一个下拉列表:

    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
            );
    }

2 个答案:

答案 0 :(得分:1)

首先,制作一个新方法来获得如下所示的描述:

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();
        }

然后在你的助手中使用它:

    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
        );
}

答案 1 :(得分:0)