【问题标题】:Can't get DisplayAttribute Name无法获取 DisplayAttribute 名称
【发布时间】:2011-04-27 19:08:14
【问题描述】:

我有一个从 EF4 生成的部分类,我分配了一个 MetadataType 以便在 ASP.NET MVC3 上显示控件的名称,它可以按预期工作。

我想使用分配给每个属性的相同DisplayAttribute 来检索显示的属性的Name 值用于其他目的。我的课是这样的:

using Domain.Metadata;

namespace Domain
{
    [MetadataType(typeof(ClassAMetada))]
    public partial class ClassA
    {}
}

namespace Domain.Metadata
{
    public class ClassAMetada
    {
        [Display(Name = "Property 1 Description", Order = 1)]
        public Boolean Property1;

        [Display(Name = "Property 2 Description", Order = 2)]
        public Boolean Property2;
    }
}

我已经看过这 3 个帖子并尝试了提出的解决方案:

但它们都不能检索属性Name 值;未找到该属性,因此为 null,因此它返回一个空字符串(第 3 个问题)或属性名称(第 1 个问题);为了发现属性,第二个问题略有改变,但结果也是一个空字符串。

你能帮我解决这个问题吗?非常感谢!

编辑:

这是我用来检索属性值的 2 种方法的代码(两者都单独工作)。两者非常相似:第一个使用带有属性名称的字符串,另一个使用 Lamba 表达式。

private static string GetDisplayName(Type dataType, string fieldName)
{
    DisplayAttribute attr;
    attr = (DisplayAttribute)dataType.GetProperty(fieldName).GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault();

    if (attr == null)
    {
        MetadataTypeAttribute metadataType = (MetadataTypeAttribute)dataType.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault();
        if (metadataType != null)
        {
            var property = metadataType.MetadataClassType.GetProperty(fieldName);
            if (property != null)
            {
                attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault();
            }
        }
    }
    return (attr != null) ? attr.Name : String.Empty;
}


private static string GetPropertyName<T>(Expression<Func<T>> expression)
{
    MemberExpression propertyExpression = (MemberExpression)expression.Body;
    MemberInfo propertyMember = propertyExpression.Member;

    Object[] displayAttributes = propertyMember.GetCustomAttributes(typeof(DisplayAttribute), true);
    if (displayAttributes != null && displayAttributes.Length == 1)
        return ((DisplayAttribute)displayAttributes[0]).Name;

    return propertyMember.Name;
}

【问题讨论】:

  • 我删除了我的答案,因为我担心我把你带错了路。您能否发布代码显示您如何尝试检索 Name 属性?
  • @Sergi Papaseit:好的,没问题;)我用我用来检索属性值的方法代码更新了我的问题。感谢您的帮助!

标签: c# .net reflection asp.net-mvc-3


【解决方案1】:

您是否考虑过将您的显示名称放入资源中?它比所有这些反射魔法更容易重用。

你可以这样做:

[Display(Name = "Property1Name", ResourceType = typeof(Resources), Order = 1)]
public Boolean Property1;

并使用Property1Name 键和“Property 1 Description”值将Resources.resx 文件添加到您的项目中。当然,您可能必须将默认资源访问权限从internal 设置为public

稍后,在其他地方您需要这些字符串只需调用:

string displayName = Domain.Resources.Property1Name;

【讨论】:

    猜你喜欢
    • 2021-09-04
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 2016-06-14
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多