0

所以我急切地将 System.ComponentModel.DataAnnotations 命名空间添加到我的模型中。

我添加了以下内容:

[Required] [DisplayName("First Name")]
public string first_name {get;set;}

我真的很喜欢这些属性,因为它们使我不必编写自定义 T4 和/或大量修改视图。这样,我可以重新生成一个视图,确信它会添加我想要的显示名称等。

当我开始构建一个受 ASP.NET MVC2 中释放的帮助器启发的 DataGrid 帮助器时,问题就出现了。

在这个助手中,Stephen 使用反射来获取列标题。

var value=typeOf(T).GetProperty(columnName).GetValue(item,null) ?? String.Empty;

好吧,问题是我不想检索属性名称。我想检索 DisplayName 属性的值。

我对此的第一次尝试是查看 PropertyInfo 类的 Attributes 属性。不幸的是,没有一个数据注释显示为属性。

有没有办法使用反射来检索数据注释?

谢谢,

罗恩

4

2 回答 2

0
public static void BuildGrid<T>(IEnumerable<T> items)
    {            
        var metadataTypes = typeof(T).GetCustomAttributes(typeof(MetadataTypeAttribute), true);
        if (metadataTypes.Any())
        {
            foreach (var metaProp in (metadataTypes[0] as MetadataTypeAttribute).MetadataClassType.GetProperties())
            {
                var objProp = typeof(T).GetProperties().Single(x => x.Name == metaProp.Name);
                var displayNames = metaProp.GetCustomAttributes(typeof (DisplayNameAttribute), true);
                if (displayNames.Any())
                {
                    var displayName = (displayNames[0] as DisplayNameAttribute).DisplayName;                        
                    foreach (var item in items)
                        var value = objProp.GetValue(item, null);                            
                }
            }                
        }
    }
于 2010-08-11T07:59:40.703 回答
0
var attributes = (DisplayNameAttribute[])typeof(T)
    .GetProperty(columnName)
    .GetCustomAttributes(typeof(DisplayNameAttribute), true);

// TODO: check for null and array size
var displayName = attributes[0].DisplayName;
于 2010-02-03T08:25:10.593 回答