How to add ModelState.AddModelError message when model item is not binded

后端 未结 3 894
野的像风
野的像风 2021-02-01 05:15

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

  
    

        
3条回答
  •  别那么骄傲
    2021-02-01 05:41

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

提交回复
热议问题