Welcome 微信登录

首页 / 网页编程 / ASP.NET / Asp.net MVC示例项目“Suteki.Shop”分析之数据验证

Asp.net MVC示例项目“Suteki.Shop”分析之数据验证2009-12-31 博客园 代震军在Suteki.Shop,实现了自己的数据校验机制,可以说其设计思路还是很有借鉴价值的。而使用这种 机制也很容易在Model中对相应的实体对象(属性)添加校验操作方法。下面就来介绍一下其实现方式。

首先,看一下这样类图:

在Suteki.Shop定 义一个“IValidatingBinder”接口,其派生自IModelBinder:

其接口中定义了一个 重载方法UpdateFrom,其要实现的功能与MVC中UpdateFrom一样,就是自动读取我们在form中定义的有些 元素及其中所包含的内容。

实现IValidatingBinder接口的类叫做:ValidatingBinder,下面是 其核心代码说明。

首先是BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)该方法是在IModelBinder接口中定义的,是其核心功能,用于将 客户端数据转成我们希望Model类型。

public virtual void UpdateFrom(BindingContext bindingContext)
{
foreach (var property in bindingContext.Target.GetType ().GetProperties())
{
try
{
foreach (var binder in propertyBinders)
{
binder.Bind(property, bindingContext);
}
}
catch (Exception exception)
{
if (exception.InnerException is FormatException ||
exception.InnerException is IndexOutOfRangeException)
{
string key = BuildKeyForModelState(property, bindingContext.ObjectPrefix);
bindingContext.AddModelError(key, bindingContext.AttemptedValue, "Invalid value for {0}".With(property.Name));
bindingContext.ModelStateDictionary.SetModelValue(key, new ValueProviderResult(bindingContext.AttemptedValue, bindingContext.AttemptedValue, CultureInfo.CurrentCulture));
}
else if (exception is ValidationException)
{
string key = BuildKeyForModelState(property, bindingContext.ObjectPrefix);
bindingContext.AddModelError(key, bindingContext.AttemptedValue, exception.Message);
bindingContext.ModelStateDictionary.SetModelValue(key, new ValueProviderResult (bindingContext.AttemptedValue, bindingContext.AttemptedValue, CultureInfo.CurrentCulture));
}
else if (exception.InnerException is ValidationException)
{
string key = BuildKeyForModelState(property, bindingContext.ObjectPrefix);
bindingContext.AddModelError(key, bindingContext.AttemptedValue, exception.InnerException.Message);
bindingContext.ModelStateDictionary.SetModelValue(key, new ValueProviderResult (bindingContext.AttemptedValue, bindingContext.AttemptedValue, CultureInfo.CurrentCulture));
}
else
{
throw;
}
}

}
if (!bindingContext.ModelStateDictionary.IsValid)
{
throw new ValidationException("Bind Failed. See ModelStateDictionary for errors");
}
}