25

I am new to MVC4. Here I added the ModelState.AddModelError message to display when the delete operation is not possible.

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


In my controller

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

Here I didnt pass any of the model item in the View to check for the item in Model and I couldnt get the ModelState error message ..
Any suggestions

4

3 回答 3

35

The ModelState is created at each request so you should use 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();
}
于 2012-10-17T14:49:55.767 回答
12

RedirectToAction will clear ModelState. You must return a view in order to use this data. Therefore, the first if case won't work. Also, ensure that you have a control in your view (like ValidationSummary) which displays the error... this could be the problem in the second case.

于 2012-10-17T14:32:32.843 回答
2

The RedirectToAction method returns 302 which causes the client to be redirected. Because of this the ModelState is lost as the redirect is a new request. You could however, use the TempData property which allows you to store a temporary piece of data that is unique to the session. You could then check for this TempData on the other controller and add a ModelState error in that method.

于 2012-10-17T14:39:27.393 回答