Validating DataAnnotations with Validator class

前端 未结 2 1214
-上瘾入骨i
-上瘾入骨i 2020-12-07 19:14

I\'m trying to validate a class decorated with data annotation with the Validator class.

It works fine when the attributes are applied to the same class. But when I

相关标签:
2条回答
  • 2020-12-07 19:26

    I found the answer here: http://forums.silverlight.net/forums/p/149264/377212.aspx

    MVC recognizes the MetaDataType attribute, but other projects do not. Before validating, you need to manually register the metadata class:

    TypeDescriptor.AddProviderTransparent(
                new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Persona), typeof(Persona_Validation)), typeof(Persona));
    
    ValidationContext context = new ValidationContext(p, null, null);
    List<ValidationResult> results = new List<ValidationResult>();
    
    bool valid = Validator.TryValidateObject(p, context, results, true);
    
    0 讨论(0)
  • 2020-12-07 19:26

    Try to move the metadata class into the same namespace as the Persona class if it isn't already. I was having similar problems and moving my metadata class into the same namespace as the L2S model class worked for me.

    0 讨论(0)
提交回复
热议问题