Asp.net MVC源码分析--Model Validation(Server端)实现(2)
前面我们介绍了Model Validation的用法,以及ValidateModel的方法实现,这一篇我们来详细学习一下DataAnnotationsModelValidatorProvider类的实现。
三.DataAnnotationsModelValidatorProvider类详解
1.AttributeFactories对象
首先在这个类中可以看到在初始化时创建了AttributeFactories对象(Dictionary), 这个集合包含了系统内置一些验证规则。
1 internal static Dictionary<Type, DataAnnotationsModelValidationFactory> AttributeFactories = new Dictionary<Type, DataAnnotationsModelValidationFactory>() {
2 {
3 typeof(RangeAttribute),
4 (metadata, context, attribute) => new RangeAttributeAdapter(metadata, context, (RangeAttribute)attribute)
5 },
6 {
7 typeof(RegularExpressionAttribute),
8 (metadata, context, attribute) => new RegularExpressionAttributeAdapter(metadata, context, (RegularExpressionAttribute)attribute)
9 },
10 {
11 typeof(RequiredAttribute),
12 (metadata, context, attribute) => new RequiredAttributeAdapter(metadata, context, (RequiredAttribute)attribute)
13 },
14 {
15 typeof(StringLengthAttribute),
16 (metadata, context, attribute) => new StringLengthAttributeAdapter(metadata, context, (StringLengthAttribute)attribute)
17 },
18 }
19 }
复制代码
2.ValidationAttribte 的 Adapter 设计模式应用
这里特别需要注意的是MVC利用了*AttributeAdapter 把 ValidationAttribte 的GetValidationResult方法和 ModelValidator.Validate方法作了一个适配(这里用到Adapter模式)请看RangeAttributeAdapter/RegularExpressionAttributeAdapter/RequiredAttributeAdapter/StringLengthAttributeAdapter
请参照DataAnnotationsModelValidator.Validate 方法源码,第7行代码,就是在这里进行了适配的工作。
1 public override IEnumerable<ModelValidationResult> Validate(object container) {
2 // Per the WCF RIA Services team, instance can never be null (if you have
3 // no parent, you pass yourself for the "instance" parameter).
4 ValidationContext context = new ValidationContext(container ?? Metadata.Model, null, null);
5 context.DisplayName = Metadata.GetDisplayName();
6
7 ValidationResult result = Attribute.GetValidationResult(Metadata.Model, context);
&nb
- 发表评论
-
- 最新评论 进入详细评论页>>
今日头条
更多>>您可能感兴趣的文章
- asp.net DataTable和Dataset序列化成Json格式
- .NET设计模式:工厂方法模式(Factory Method)[1]
- MVC3+Entity Framework 实现投票系统(二)
- 聊聊.net程序设计——浅谈使用VS2010建模拓展(下
- Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注
- Web Service学习笔记(4)
- 使用ASP.NET MVC3+EF+Jquery制作文字直播系统(四
- .NET简谈互操作(四:基础知识之Dispose非托管内存
- JQuery+Asp.net MVC实现用户名重名查询
- .net架构的最后思考(箴言)



