【问题标题】:How can I access the DisplayName data annotation value from code?如何从代码中访问 DisplayName 数据注释值?
【发布时间】:2010-08-15 00:41:18
【问题描述】:
public static string ProductHelper(this Product p) {
    // Need to get the DisplayName value for p.Name property
}

编辑:

[MetadataType(typeof(ProductMetadata))]
public partial class Product {
    public class ProductMetadata {
        [DisplayName("Product name")]
        public object Name { get; set; }
    }
}

【问题讨论】:

    标签: asp.net-mvc-2 data-annotations


    【解决方案1】:
    Type type = typeof(Product);
    DisplayNameAttribute att = (DisplayNameAttribute)type.GetProperty("Name").GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault();
    

    这假定属性始终存在。修改可能不可用的情况。

    编辑:
    获取值string x = att.DisplayName;

    如果 Product 是基类,请改用Type type = p.GetType();

    【讨论】:

    • 如果产品的 Name 属性的 DisplayName 是通过 MetaData 类 (ProductMetaData) 提供的怎么办?请查看编辑后的更新。
    • 检查该属性的类并获取对指定类型的引用。反省一下该类型的属性。
    • 我在部分类中有属性注释,但我有 0 个 customAttributes,为什么?
    猜你喜欢
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多