1

I have a partial class generated from a web service. I add ModelMetadata to this class like so:

// Automatically generated code

public partial class MyClass
{
    public string FIELD_ONE ...
    public DateTime? FIELD_TWO ...
}

// My code

[MetadataType(typeof(MyMetaDataClass))]
public partial class MyClass
{
}

public class MyMetaDataClass
{
    [Display(Name="Field One")] 
    public string FIELD_ONE;

    [Display(Name="Field Two")] 
    public DateTime? FIELD_TWO;
}

Now I would like to get all properties of MyClass which have metadata Display Attributes, ie, FIELD_ONE and FIELD_TWO.

I've tried things like

typeof(MyClass).GetProperties().Where(p => Attribute.IsDefined(typeof(DisplayAttribute))

But of course the attribute is not on the properties of MyClass. I've also tried:

ModelMetadata mmd = ModelMetadata.FromLambdaExpression(m => pi.GetValue(m, null), Html.ViewData);

But I get the error "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."

If I could get from MyClass to MyMetadataClass I might then be able to get the property names of that and get the properties of the same name from MyClass.

Is this possible, or am I barking up the wrong tree?

Jamie Kitson
  • 3,973
  • 4
  • 37
  • 50
  • check this this out , i already answered this question here http://stackoverflow.com/a/24757520/3050647 – elia07 Jul 15 '14 at 12:18

1 Answers1

2

What is it exactly that you are trying to do? If you want to override what the default metadata provider does, then you are probably better off replacing DataAnnotationsModelMetadataProvider with your own implementation. Here is some example code:

http://buildstarted.com/2010/09/14/creating-your-own-modelmetadataprovider-to-handle-custom-attributes/

Here, the author is adding support for his own custom attributes but you can just as easily override the default implemntation for the DisplayAttribute.

if this is not helpful, please give more detail as to what you are trying to achieve.

Matt
  • 6,787
  • 11
  • 65
  • 112
  • In the example I want to be able to iterate through `FIELD_ONE` and `FIELD_TWO` on a 'MyClass' object automatically. – Jamie Kitson Mar 06 '13 at 14:32