2011-12-30 26 views
1

我有一個關於ModelState和MVC3驗證錯誤消息的問題。 我在我的註冊視圖中顯示@Html.ValidationSummary(false),它顯示我的Model對象的DataAnnotations錯誤消息。然後..在我的註冊行動控制器我有ModelState.IsValid,但在裏面if(ModelState.IsValid)我有另一個錯誤控制,添加到ModelState.AddModelError(string.Empty, "error...")模型狀態,然後我做RedirectToAction,但在ModelState添加的消息根本不顯示。添加模型狀態錯誤並在重定向到動作後生效

爲什麼會發生這種情況?

回答

4

,然後我做一個RedirectToAction

那是你的問題。重定向模型時,狀態值將丟失。添加到模型狀態的值(包括錯誤消息)僅在當前請求的生命週期中存在。如果重定向它是一個新的請求,那麼modelstate會丟失。通常的POST動作流程如下:

[HttpPost] 
public ActionResult Foo(MyViewModel model) 
{ 
    if (!ModelState.IsValid) 
    { 
     // there were some validation errors => we redisplay the view 
     // in order to show the errors to the user so that he can fix them 
     return View(model); 
    } 

    // at this stage the model is valid => we can process it 
    // and redirect to a success action 
    return RedirectToAction("Success"); 
} 
+0

嗯...所以..我需要做一個返回視圖()?..但視圖是在另一個控制器..(是的,我知道,也許這是錯誤的..但在這一點上,我想我沒有時間去改變它:S) – 2011-12-30 18:59:44

+0

@Phoenix_uy對於一個「快速」修復添加到共享目錄的視圖,因爲它是專門共享視圖跨多個控制器。 – Jesse 2011-12-30 19:24:43

相關問題