简体   繁体   中英

How do Data Annotations work?

I use Data Annotations in my ASP.NET MVC 3 project to validate the model. These are extremely convenient but currently they are magic to me. I read that data annotations do not throw exceptions. How then does MVC know to add validation errors to the model state dictionary? How does the failure to set a property on the model because of model validation bubble up to MVC if no exception is thrown? I always assumed that exceptions were thrown every time a property failed and that MVC model binding caught the exception and added it to the model state dictionary.

To test this I created a console application and added a sample class with a validation annotation to it:

public class MyObject
{
    [StringLength(10, MinimumLength=3)]
    public string Name { get; set; }
}

I then instantiated the object and tried to assign values to the Name property that were less than 3. The property assigned just fine, despite the annotation that says string length of less than 3 is not allowed.

    static void Main(string[] args)
    {
        MyObject mine = new MyObject();
        mine.Name = "hi";
        Console.WriteLine(mine.Name);
        Console.ReadLine();
    }

This little program writes out "hi" to the console. Why? I was expecting it to get angry when trying to set mine.Name to "hi".

What am I missing?

Thanks in advance.

You never call anything to validate the properties. The validation doesn't happen magically on its own. from http://msdn.microsoft.com/en-us/library/dd901590%28v=vs.95%29.aspx

Manually Validating Values

When you do not use the DataGrid control to provide the interface for editing data, the validation attributes are not automatically applied. However, you can manually apply the validation test by using the Validator class. You can call the ValidateProperty method on the set accessor of a property to check the value against the validation attributes for the property. You must also set both ValidatesOnExceptions and NotifyOnValidationError properties to true when data binding to receive validation exceptions from validation attributes. For an example of manually applying validation, see the Data Binding Example below.

C# provides a mechanism for defining declarative tags, called attributes, which you can place on certain entities in your source code to specify additional information. The information that attributes contain can be retrieved at run time through reflection.

https://msdn.microsoft.com/en-us/library/aa288059(v=vs.71).aspx

Here are three articles to help expand your knowledge of how attributes work. The last being the least important if you understand how to use them. The article is for silverlight but is still applicable to the topic at hand.

Introduction to Attributes

Attributes

DataTypeAttributes

Using Data Annotations w/ silverlight

How then does MVC know to add validation errors to the model state dictionary?

ModelValidatorProvider , more specifically, DataAnnotationsModelValidatorProvider . This is called by MVC.

because you are not checking if the model is valid... the data notation checks the validity of the model. then you will get your error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM