DataTypeAttribute 是 DefaultModelBinder 类的验证属性吗
我刚刚注意到 DataTypeAttribute
类是从 System.ComponentModel.DataAnnotations.ValidationAttribute
继承的。
就 ASP.NET MVC DefaultModelBinder
类而言,DataTypeAttribute
是验证属性吗?简而言之,ModelBinder 是否根据 DataTypeAttribute 验证对象?
例如,如果我将 DataType
属性指定为 DataType.EmailAddress
,它会验证电子邮件地址还是该属性仅提供对象的元数据。
更新
我在SO上发现了类似的问题:
是DataTypeAttribute 验证在 MVC2 中工作吗?
因此,根据它,它不能作为验证属性工作。那么,如果它不用作验证属性,为什么要从 System.ComponentModel.DataAnnotations.ValidationAttribute 继承呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DataTypeAttribute 本身不包含任何验证逻辑。
它派生自 ValidationAttribute 的原因是,您可以创建一个新的自定义数据类型类,它既是 DataType 又是 Validation,两者都包装在一起。这是 .NET 不允许多重继承的一个不幸的副作用。
所以,是的,它是一个验证器......默认情况下不进行验证。它正在耐心地等待您完成繁重的工作。 :)
实际上,如果您查看 MVC 3 Futures 内部,您会发现我们利用它来创建新的自定义验证器,我们知道 jQuery 已经能够提供客户端验证逻辑,并且我们添加了镜像服务器端验证逻辑(并保留了数据类型对模板的好处)。
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).
基于 MVC3 源代码,
DataTypeAttribute
的唯一目的是填充ModelMetadata.DataTypeName
属性 。并且此属性仅由EditorFor/DisplayFor 模板生成。所以你是对的,这与验证无关。所以我不知道为什么它是从ValidationAttribute
继承的。也许框架作者将其保留以供将来使用。Based on the MVC3 source code the only purpose of the
DataTypeAttribute
is to populate theModelMetadata.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 fromValidationAttribute
. Maybe the framework authors reserved it for future use.