ASP.Net MVC 3 ModelState.IsValid

w.d*_*hue 5 asp.net-mvc-3

我刚刚开始使用ASP.Net MVC 3并且在这一点上感到困惑.

在某些示例中,当运行包含输入的控制器中的操作时,将进行检查以确保ModelState.IsValid为true.某些示例未显示正在进行此检查.我应该什么时候进行检查?每当向动作方法提供输入时,是否必须使用它?

Dar*_*rov 8

每当向动作方法提供输入时,是否必须使用它?

正是在使用作为操作参数提供的视图模型时,此视图模型具有与之关联的一些验证(例如数据注释).这是通常的模式:

public class MyViewModel
{
    [Required]
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后:

[HttpPost]
public ActionResult Foo(MyViewModel model)
{
    if (!ModelState.IsValid)
    {
        // the model is not valid => we redisplay the view and show the
        // corresponding error messages so that the user can fix them:
        return View(model);
    }

    // At this stage we know that the model passed validation 
    // => we may process it and redirect
    // TODO: map the view model back to a domain model and pass this domain model
    // to the service layer for processing

    return RedirectToAction("Success");
}
Run Code Online (Sandbox Code Playgroud)