I have a class that defines data annotations at class level. The meta data class has custom attributes associated with it, along with the usual DisplayName, DisplayFormat etc.
public class BaseMetaData
{
[DisplayName("Id")]
public object Id { get; set; }
[DisplayName("Selected")]
[ExportItem(Exclude = true)]
public object Selected { get; set; }
}
[MetadataType(typeof(BaseMetaData))]
public class BaseViewModel
{
public int Id { get; set; }
public bool Selected { get; set; }
Given a type T, how can I retrieve the custom attributes from the meta data class? The attempt below would not work as the metadata properties are from the BaseViewModel rather than the BaseMetaData class.
Needs to work generically i.e. can't do typeof(BaseMetaData).GetProperty(e.PropertyName). Wondering if there is a way of getting the MetadataType from the class then it would make it possible.
var type = typeof (T);
var metaData = ModelMetadataProviders.Current.GetMetadataForType(null, type);
var propertMetaData = metaData.Properties
.Where(e =>
{
var attribute = type.GetProperty(e.PropertyName)
.GetCustomAttributes(typeof(ExportItemAttribute), false)
.FirstOrDefault() as ExportItemAttribute;
return attribute == null || !attribute.Exclude;
})
.ToList();
Based on the other answers, i'm successed to get the DisplayName attribute from MetadataType class in this way:
Found a solution by using the type of MetadataTypeAttribute to get the custom attributes.
Have you tried just doing this,
You can then use a variation of your code,
I was looking for something similar, and looking at the class MetadataTypeAttribute, I realice that it stores the type of the Metdata class. Inside that class, you can have get/set properties, or just fields (get/set properties are defined in one partial class, like autogenerated models in MVC), so, I read the fields within that metadata class, then get the atributes for the field. Code is:
Result I see is: