是DataTypeAttribute被验证属性DefaultModelBinder类属性、DataTypeAttribute、DefaultModelBinder

2023-09-06 18:51:27 作者:你与氧共存

我刚才注意到 DataTypeAttribute 类是从 System.ComponentModel.DataAnnotations.ValidationAttribute 继承。

I have just noticed that DataTypeAttribute class is inherited from System.ComponentModel.DataAnnotations.ValidationAttribute.

在ASP.NET MVC方面 DefaultModelBinder 类,是 DataTypeAttribute 是一个验证的属性?在简单的英语,并ModelBinder的根据 DataTypeAttribute

In terms of ASP.NET MVC DefaultModelBinder class, is DataTypeAttribute is a validation attribute? In plain English, does ModelBinder validate the object according to DataTypeAttribute?

例如,如果我指定数据类型属性 DataType.EmailAddress ,它会验证电子邮件地址或者这个属性仅提供元数据的对象。

For example, if I specify DataType property to DataType.EmailAddress, will it validate the e-mail address or this attribute is only providing metadata for objects.

更新

我发现SO一个类似的问题:

I found a similar question on SO :

Is在DataTypeAttribute验证在MVC2工作?

因此​​,根据它不工作作为验证属性。那么,为什么它是从 System.ComponentModel.DataAnnotations.ValidationAttribute 继承的,如果它不作为验证属性?

So, according to that it is not working as a validation attribute. So, why it is inherited from System.ComponentModel.DataAnnotations.ValidationAttribute if it is not serving as a validation attribute?

推荐答案

DataTypeAttribute不包含任何验证逻辑本身。

DataTypeAttribute does not contain any validation logic itself.

从ValidationAttribute派生的原因是,你可以创建一个新的自定义数据类型的类,这既是一种数据类型和验证,所有包裹成一个。它是.NET不允许多重继承的不幸的副作用。

The reason it derives from ValidationAttribute is so that you could create a new custom data type class, which was both a DataType and a Validation, all wrapped up into one. It's an unfortunate side-effect of .NET not allowing multiple inheritance.

所以,是的,这是一个验证器......这不会验证默认情况下。它耐心地等待你做繁重。 :)

So, yes, it's a validator... that does no validation by default. It's waiting patiently for you to do the heavy lifting. :)

其实,如果你的MVC 3期货里面,你会看到,我们利用它来创建新的自定义的验证器,我们知道的jQuery已经能够提供客户端验证逻辑,而我们增加了镜像服务器端验证逻辑(和preserved为模板的数据类型的好处)。

Actually, if you look inside of MVC 3 Futures, you'll see that we leveraged this to create new custom validators where we knew that jQuery was already capable of providing client-side validation logic, and we added mirrored server-side validation logic (and preserved the DataType benefits for templating).