views:

104

answers:

2

Hi,

So I've eagerly added the System.ComponentModel.DataAnnotations namespace to my model.

I've added things such as:

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

I really like these attributes because they save me from having to write custom T4 and/or modify views heavily. This way, I can regenerate a view confident that it will add the display names I want, etc.

The problem comes in when I started building a DataGrid helper inspired by the one in ASP.NET MVC2 unleashed.

In this helper, Stephen uses reflection to get at the column headings.

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

Well, the trouble is I don't want to retrieve the property name. I want to retrieve the value for the DisplayName attribute.

My first attempt at this was to look inside the Attributes property of the PropertyInfo class. Unfortunately, none of the data annotations show up as an attribute.

Is there a way to retrieve the data annotations using reflection?

Thanks,

Ron

A: 
var attributes = (DisplayNameAttribute[])typeof(T)
    .GetProperty(columnName)
    .GetCustomAttributes(typeof(DisplayNameAttribute), true);

// TODO: check for null and array size
var displayName = attributes[0].DisplayName;
Darin Dimitrov
A: 
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);                            
                }
            }                
        }
    }
CoffeeCode