本文介绍了未绑定模型项时如何添加ModelState.AddModelError消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVC4的新手.在这里,我添加了ModelState.AddModelError消息,以在无法执行删除操作时显示.

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

在这里,我没有在视图中传递任何模型项来检查模型中的项,而我却没有收到ModelState错误消息..
任何建议

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

推荐答案

在每个请求中都会创建ModelState,因此您应该使用TempData.

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

这篇关于未绑定模型项时如何添加ModelState.AddModelError消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 14:11