How do Data Annotations work?

谁都会走 提交于 2019-11-28 06:21:54

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 bothValidatesOnExceptions 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.

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

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

BentOnCoding

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!