简体   繁体   English

数据注释如何工作?

[英]How do Data Annotations work?

I use Data Annotations in my ASP.NET MVC 3 project to validate the model. 我在ASP.NET MVC 3项目中使用Data Annotations来验证模型。 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? 那么MVC如何知道将验证错误添加到模型状态字典中? How does the failure to set a property on the model because of model validation bubble up to MVC if no exception is thrown? 如果没有抛出异常,由于模型验证而在模型上设置属性的失败如何冒泡到MVC? 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. 我总是假设每次属性失败时抛出异常,并且MVC模型绑定捕获异常并将其添加到模型状态字典中。

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. 然后我实例化了该对象,并尝试为Name属性分配小于3的值。尽管注释表明字符串长度小于3,但该属性分配得很好。

    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. 这个小程序向控制台写出“hi”。 Why? 为什么? I was expecting it to get angry when trying to set mine.Name to "hi". 当我试图将mine.Name设置为“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 来自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. 如果不使用DataGrid控件提供编辑数据的界面,则不会自动应用验证属性。 However, you can manually apply the validation test by using the Validator class. 但是,您可以使用Validator类手动应用验证测试。 You can call the ValidateProperty method on the set accessor of a property to check the value against the validation attributes for the property. 您可以在属性的set访问器上调用ValidateProperty方法,以根据属性的验证属性检查值。 You must also set both ValidatesOnExceptions and NotifyOnValidationError properties to true when data binding to receive validation exceptions from validation attributes. 当数据绑定从验证属性接收验证异常时,还必须将ValidatesOnExceptionsNotifyOnValidationError属性都设置为true。 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. C#提供了一种定义声明性标记的机制,称为属性,您可以将其置于源代码中的某些实体上以指定其他信息。 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 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. 这篇文章是针对silverlight的,但仍然适用于手头的主题。

Introduction to Attributes 属性简介

Attributes 属性

DataTypeAttributes DataTypeAttributes

Using Data Annotations w/ silverlight 使用带有silverlight的数据注释

How then does MVC know to add validation errors to the model state dictionary? 那么MVC如何知道将验证错误添加到模型状态字典中?

ModelValidatorProvider , more specifically, DataAnnotationsModelValidatorProvider . ModelValidatorProvider ,更具体地说, DataAnnotationsModelValidatorProvider This is called by MVC. 这是由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. 然后你会得到你的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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