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

时间:2011-06-21 22:13:57

标签: asp.net-mvc

我想使用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", "Unfortunately, we cannot serve your address.");

if (bar.isDuplicate())
    ModelState.AddModelError("OrderNumber", "This appears to be a duplicate order");

5 个答案:

答案 0 :(得分:5)

如果您使用的是MVC 3,则应该结帐IValidatableObject,这就是您所追求的目标。

Scott Gu在他的MVC3 Intro博客帖子中提到了这一点。

答案 1 :(得分:1)

您可以使用自定义数据注释或使用RuleViolations(例如this示例中的内容)执行NerdDinner之类的操作。

答案 2 :(得分:0)

也许您可以创建一个错误接口,如IErrorHandler,并将其传递给模型类中名为Validate的公共方法,假设它是一个部分类,您可以从规则中分离数据模型。

使用该接口,您可以在控制器中创建一个包装ModelState错误处理程序的类。所以接口可能有AddError,并且metghod tou只委托给你的本地模型状态。

所以你的方法可能是这样的:

IErrorHandler errorHandler = CreateErrorHandler();
model.Validate(errorHandler);

if(errorHandler.IsValid())
... do something

答案 3 :(得分:0)

您可以通过模型上的IValidatableObject接口使用自定义验证。

Custom validation example

答案 4 :(得分:0)

如果你的代码数量最少,那么这种做法就是将这条消息从Session中填入View Model,然后从{{1}添加该消息例如:

Controller

让我重申,我意识到这有点像hacky,但它很简单,它完成了工作......