Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DisplayAttribute attribute from PropertyInfo

class SomeModel
{
    [Display(Name = "Quantity Required")]
    public int Qty { get; set; }

    [Display(Name = "Cost per Item")]
    public int Cost { get; set; }
}

I'm trying to map the model into a list of { PropertyName, DisplayName } pairs, but I've got stuck.

var properties 
    = typeof(SomeModel)
        .GetProperties()
        .Select(p => new 
            {
                p.Name,
                p.GetCustomAttributes(typeof(DisplayAttribute),
                              false).Single().ToString()
            }
        );

The above doesn't compile and I'm not sure it's the right approach anyway, but hopefully you can see the intent. Any pointers? Thanks

like image 565
fearofawhackplanet Avatar asked Sep 07 '11 14:09

fearofawhackplanet


1 Answers

In this case you need to define specific property names for anonymous type.

var properties = typeof(SomeModel).GetProperties()
    .Where(p => p.IsDefined(typeof(DisplayAttribute), false))
    .Select(p => new
        {
            PropertyName = p.Name,
            DisplayName = p.GetCustomAttributes(typeof(DisplayAttribute),
                false).Cast<DisplayAttribute>().Single().Name
        });
like image 128
Kirill Polishchuk Avatar answered Sep 30 '22 07:09

Kirill Polishchuk