2012-10-17 39 views
20

我是MVC4的新手。在這裏,我添加了ModelState.AddModelError消息,以便在刪除操作不可用時顯示。
如何在未綁定模型項時添加ModelState.AddModelError消息

<td> 
    <a id="aaa" href="@Url.Action("Delete", "Shopping", new { id = Request.QueryString["UserID"], productid = item.ProductID })" style="text-decoration:none"> 
    <img alt="removeitem" style="vertical-align: middle;" height="17px" src="~/Images/remove.png" title="remove" id="imgRemove" /> 
     </a> 
     @Html.ValidationMessage("CustomError") 
    </td> 
    @Html.ValidationSummary(true) 


在我的控制器

public ActionResult Delete(string id, string productid) 
     {    
      int records = DeleteItem(id,productid); 
      if (records > 0) 
      { 
       ModelState.AddModelError("CustomError", "The item is removed from your cart"); 
       return RedirectToAction("Index1", "Shopping"); 
      } 
      else 
      { 
       ModelState.AddModelError(string.Empty,"The item cannot be removed"); 
       return View("Index1"); 
      } 
     } 

在這裏我沒有通過任何模型中項目的視圖,以檢查模型中的項目,我不可能得到的ModelState錯誤消息。
任何建議

回答

29

ModelState是在每個請求中創建的,因此您應該使用TempData

public ActionResult Delete(string id, string productid) 
{    
    int records = DeleteItem(id,productid); 
    if (records > 0) 
    {  
     // since you are redirecting store the error message in TempData 
     TempData["CustomError"] = "The item is removed from your cart"; 
     return RedirectToAction("Index1", "Shopping"); 
    } 
    else 
    { 
     ModelState.AddModelError(string.Empty,"The item cannot be removed"); 
     return View("Index1"); 
    } 
} 

public ActionResult Index1() 
{ 
    // check if TempData contains some error message and if yes add to the model state. 
    if(TempData["CustomError"] != null) 
    { 
     ModelState.AddModelError(string.Empty, TempData["CustomError"].ToString()); 
    } 

    return View(); 
} 
7

RedirectToAction將清除ModelState。您必須返回一個視圖才能使用這些數據。因此,第一個「if」情況將不起作用。此外,請確保您在視圖中具有控件(如ValidationSummary),該控件顯示錯誤...這可能是第二種情況中的問題。

2

RedirectToAction方法返回302,導致客戶端被重定向。由於這個原因,模型狀態會丟失,因爲重定向是一個新的請求。但是,您可以使用TempData屬性,該屬性允許您存儲會話特有的臨時數據片段。然後,您可以在另一個控制器上檢查此TempData,並在該方法中添加一個ModelState錯誤。

相關問題