【问题标题】:Create dropdown list for enum with description C#使用描述 C# 为枚举创建下拉列表
【发布时间】:2014-03-07 09:35:31
【问题描述】:

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

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

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

【问题讨论】:

标签: c# enums html.dropdownlistfor


【解决方案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
        );
}

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      • 2017-11-30
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      相关资源
      最近更新 更多