Is DataTypeAttribute is a validation attribute For DefaultModelBinder Class

自闭症网瘾萝莉.ら 提交于 2019-12-11 08:44:29

问题


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

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?

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.

UPDATE

I found a similar question on SO :

Is the DataTypeAttribute validation working in MVC2?

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?


回答1:


DataTypeAttribute does not contain any validation logic itself.

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. :)

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




回答2:


Based on the MVC3 source code the only purpose of the DataTypeAttribute is to populate the ModelMetadata.DataTypeName property .And this property is only used by the EditorFor/DisplayFor template generation. So you were right it has nothing to do with validation. So I don't know why is it inherited from ValidationAttribute. Maybe the framework authors reserved it for future use.



来源:https://stackoverflow.com/questions/8107252/is-datatypeattribute-is-a-validation-attribute-for-defaultmodelbinder-class

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