2012-10-17 25 views
20

Tôi mới dùng MVC4. Ở đây tôi đã thêm thông báo ModelState.AddModelError để hiển thị khi không thể thực hiện thao tác xóa.
Cách thêm thông báo ModelState.AddModelError khi mục mẫu không bị ràng buộc

<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) 


Trong điều khiển của tôi

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

Ở đây tôi didnt vượt qua bất kỳ của mặt hàng mô hình trong Xem để kiểm tra các mục trong mẫu và tôi couldnt nhận được thông báo lỗi ModelState. .
Mọi đề xuất

Trả lời

29

ModelState được tạo theo từng yêu cầu, do đó bạn nên sử dụng 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 sẽ xóa ModelState. Bạn phải trả lại chế độ xem để sử dụng dữ liệu này. Do đó, trường hợp "if" đầu tiên sẽ không hoạt động. Ngoài ra, hãy đảm bảo rằng bạn có một điều khiển trong chế độ xem của mình (như ValidationSummary) hiển thị lỗi ... đây có thể là sự cố trong trường hợp thứ hai.

2

Phương thức RedirectToAction trả về 302 khiến khách hàng được chuyển hướng. Bởi vì điều này ModelState bị mất khi chuyển hướng là một yêu cầu mới. Tuy nhiên, bạn có thể sử dụng thuộc tính TempData cho phép bạn lưu trữ một đoạn dữ liệu tạm thời duy nhất cho phiên. Sau đó bạn có thể kiểm tra TempData này trên bộ điều khiển khác và thêm một lỗi ModelState trong phương thức đó.

Các vấn đề liên quan