2011-11-14 140 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,那是因爲他們的行爲沒有將任何視圖模型作爲參數,所以默認的模型綁定器沒有向模型狀態添加任何潛在的錯誤消息。 –