我想使用ModelState.AddModelError()在ASP.MVC 3输入表单中向用户显示错误,以便它自动突出显示右侧字段并将错误放在特定字段旁边.
在大多数示例中,我看到ModelState.AddModelError()和if(ModelState.IsValid)放在Controller中.但是,我想将验证逻辑移动/集中到模型类.我可以让模型类检查模型错误并填充ModelState.AddModelError()吗?
现行代码:
// Controller [HttpPost] public ActionResult Foo(Bar bar) { // This model check is run here inside the controller. if (bar.isOutsideServiceArea()) ModelState.AddModelError("Address","Unfortunately,we cannot serve your address."); // This is another model check run here inside the controller. if (bar.isDuplicate()) ModelState.AddModelError("OrderNumber","This appears to be a duplicate order"); if (ModelState.IsValid) { bar.Save(); return RedirectToAction("Index"); } else return View(bar) }
期望代码:
// Controller [HttpPost] public ActionResult Foo(Bar bar) { // something here to invoke all tests on bar within the model class if (ModelState.IsValid) { bar.Save(); return RedirectToAction("Index"); } else return View(bar) } ... // Inside the relevant Model class if (bar.isOutsideServiceArea()) ModelState.AddModelError("Address",we cannot serve your address."); if (bar.isDuplicate()) ModelState.AddModelError("OrderNumber","This appears to be a duplicate order");
解决方法
如果你正在使用MVC 3,你应该结账
IValidatableObject,这就是你所追求的.
Scott Gu在他的MVC3 Intro博客文章中提到了这一点.