2011-11-14 143 views
4

我刚刚开始使用ASP.Net MVC 3,并对此感到困惑。ASP.Net MVC 3 ModelState.IsValid

在某些包含输入的控制器中的操作中,执行检查以确保ModelState.IsValid为true。有些示例不显示正在进行的检查。我应该什么时候做这个检查?当输入提供给动作方法时,是否必须使用它?

回答

7

无论何时向操作方法提供输入,都必须使用它吗?

恰恰当您使用作为动作参数提供的视图模型并且此视图模型具有与其关联的某些验证(例如数据注释)时。下面是通常的模式:

public class MyViewModel 
{ 
    [Required] 
    public string Name { get; set; } 
} 

然后:

[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"); 
} 
2

是。它主要用于标记[HttpPost]属性的操作。

imho视图模型应始终进行验证(因此始终有一些验证,通常是DataAnnotation属性)。

public class MyViewModel 
{ 
    [Required] // <-- this attribute is used by ModelState.IsValid 
    public string UserName{get;set;} 
} 

如果你有兴趣在MVC错误处理,我有一个blogged about it前两天。

+0

抱歉挑剔,但说“ModelState.IsValid”使用'[Required]'属性是不正确的。它被默认的模型绑定器使用,该绑定器在将请求值绑定到视图模型时将错误消息插入到ModelState中。 –

+0

我知道,但是对于一个刚刚想要进行基本验证工作的新用户而言,这与它无关。 – jgauffin

+1

恕我直言,即使有新用户,我们也应尽可能精确。例如,你将这个注释放在你的答案中,不熟悉ASP.NET MVC内部工作的人可能会认为它是触发验证的'ModelState.IsValid'调用,这显然是不正确的。例如,我看到有人问为什么ModelState.IsValid总是返回true,那是因为他们的行为没有将任何视图模型作为参数,所以默认的模型绑定器没有向模型状态添加任何潜在的错误消息。 –