【问题标题】:Get [Display] attribute value from resource in MVC从 MVC 中的资源中获取 [Display] 属性值
【发布时间】:2013-05-09 23:44:42
【问题描述】:

我已将[Display] 属性用于我的一个枚举:

    public enum eCommentType
    {
        [Display(ResourceType = typeof(FaultManagementStrings), Name = "NormalComment")]
        NormalComment = 0,

        [Display(ResourceType = typeof(FaultManagementStrings), Name = "OpenningComment")]
        OpenningComment = 1,

        [Display(ResourceType = typeof(FaultManagementStrings), Name = "StartProgressComment")]
        StartProgressComment = 2,

        [Display(ResourceType = typeof(FaultManagementStrings), Name = "ClouserComment")]
        ClouserComment = 3,

        [Display(ResourceType = typeof(FaultManagementStrings), Name = "ReopennignComment")]
        ReopennignComment = 4
    }

是否可以创建一个扩展方法来重用现有的 MVC 功能,即从指定资源中获取 Display 属性值?

我想要那样的东西......

@Html.GetEnumDisplayAttributeValue(c=> comment.CommentType)

我知道我可以写一些东西来实现所需的反射并找到资源类型的值和调用资源管理器等等......但我认为也许可以使用现有的内置功能mvc.. 毕竟当你调用 LabelFor 助手时它已经完成了。

是可能的还是我应该重新发明轮子?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 reflection data-annotations html-helper


    【解决方案1】:

    我也遇到了同样的问题并创建了这些扩展方法:

    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Web.Mvc;
    using System.Web.Mvc.Html;
    
    public static class EnumHelper
    {
        private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = string.Empty, Value = string.Empty } };
    
        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
        {
            return htmlHelper.EnumDropDownListFor(expression, null);
        }
    
        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
        {
            var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var enumType = GetNonNullableModelType(metadata);
            var values = Enum.GetValues(enumType).Cast<TEnum>();
    
            var items =
                values.Select(value => new SelectListItem
                                           {
                                               Text = GetName(value),
                                               Value = value.ToString(),
                                               Selected = value.Equals(metadata.Model)
                                           });
    
            if (metadata.IsNullableValueType)
            {
                items = SingleEmptyItem.Concat(items);
            }
    
            return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
        }
    
        private static string GetName<TEnum>(TEnum value)
        {
            var displayAttribute = GetDisplayAttribute(value);
    
            return displayAttribute == null ? value.ToString() : displayAttribute.GetName();
        }
    
        private static DisplayAttribute GetDisplayAttribute<TEnum>(TEnum value)
        {
            return value.GetType()
                        .GetField(value.ToString())
                        .GetCustomAttributes(typeof(DisplayAttribute), false)
                        .Cast<DisplayAttribute>()
                        .FirstOrDefault();
        }
    
        private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
        {
            var realModelType = modelMetadata.ModelType;
            var underlyingType = Nullable.GetUnderlyingType(realModelType);
    
            return underlyingType ?? realModelType;
        }
    }
    

    您可以在视图中使用这些扩展方法,如下所示:

    @Html.EnumDropDownListFor(c=> comment.CommentType)
    

    您现在应该会看到一个下拉列表,其中包含根据枚举值的 DisplayAttribute 命名的名称。

    实际检索显示的枚举值是在GetName方法中完成的,它首先使用GetDisplayAttribute方法尝试检索枚举值的DisplayAttribute。如果枚举值确实用DisplayAttribute 修饰,它将使用它来检索要显示的名称。如果没有DisplayAttribute,我们只返回枚举值的名称。

    【讨论】:

    • 你能说得更具体些吗?究竟是什么方法负责从显示属性和资源中提取信息?
    • @Mortalus 我刚刚更新了描述。您应该研究的是 GetNameGetDisplayAttribute 方法,它们用于提取显示属性。
    【解决方案2】:

    正如预期的那样,Microsoft 在MVC 5.1 (RC1) 中包含了一个EnumDropDownListFor HTML Helper 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      相关资源
      最近更新 更多