Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

DataAnnotations does not work with buddy class. The following code always validate true. Why ?

var isValid = Validator.TryValidateObject(new Customer(), Context, results, true);

and here is the buddy class.

public partial class Customer 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
}

[MetadataType(typeof(CustomerMetaData))]
public partial class Customer 
{ 
    public class CustomerMetaData 
    { 
        [Required(ErrorMessage = "You must supply a name for a customer.")]        
        public string Name { get; set; } 
    } 
}

Here is another thread with same question., but no answer. link text

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
849 views
Welcome To Ask or Share your Answers For Others

1 Answer

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(Customer), typeof(CustomerMetadata)), typeof(Customer));

var isValid = Validator.TryValidateObject(new Customer(), context, results, true);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...