我想使用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)
}
Run Code Online (Sandbox Code Playgroud)
期望代码:
// 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", "Unfortunately, we cannot serve your address.");
if (bar.isDuplicate())
ModelState.AddModelError("OrderNumber", "This appears to be a duplicate order");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13280 次 |
最近记录: |