asp.net-mvc – 我可以从Model类(而不是控制器)添加ModelState.AddModelError吗?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 我可以从Model类(而不是控制器)添加ModelState.AddModelError吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用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博客文章中提到了这一点.

猜你在找的asp.Net相关文章