模型验证(2)
模型绑定中执行验证
1.重写DefaultModelBinder
public class ValidatingModelBinder:DefaultModelBinder
{
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
{
// 调用基类
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
switch(propertyDescriptor.Name)
{
case "ClientName":
if(string.IsNullOrEmpty((string)value))
{
bindingContext.ModelState.AddModelError("ClientName","Please enter your name");
}
break;
case "Date":
if(bindingContext.ModelState.IsValidField("Date")&&DateTime.Now>((DateTime)value))
{
bindingContext.ModelState.AddModelError("Date","Please enter a date in the future");
}
break;
case "TermsAccepted":
if(!((bool)value))
{
bindingContext.ModelState.AddModelError("TermsAccepted","You must accept the terms");
}
break;
}
}
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
base.OnModelUpdated(controllerContext, bindingContext);
Appointment model = bindingContext.Model as Appointment;
if(model!=null&&bindingContext.ModelState.IsValidField("ClientName")&&bindingContext.ModelState.IsValidField("Date")&&model.ClientName=="Joe"
&&model.Date.DayOfWeek==DayOfWeek.Monday)
{
bindingContext.ModelState.AddModelError("","Joe can not book appointments on Mondays");
}
}
}
2.注册
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
DependencyResolver.SetResolver(new NinjectDependencyResolver());
ModelBinders.Binders.Add(typeof(Appointment),new ValidatingModelBinder());
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
3.修改控制器代码如下
[HttpPost]
public ViewResult MakeBooking(Appointment appt)
{
if (ModelState.IsValid)
{
repository.SaveAppointment(appt);
return View("Completed", appt);
}
else
{
return View();
}
}
Metadata验证
public class Appointment {
[Required]
public string ClientName { get; set; }
[DataType(DataType.Date)]
[Required(ErrorMessage="Please enter a date")]
public DateTime Date { get; set; }
[Range(typeof(bool),"true","true",ErrorMessage="You must accept the terms")]
public bool TermsAccepted { get; set; }
}

浙公网安备 33010602011771号