How do I maintain ModelState errors when using RedirectToAction?

后端 未结 5 1531
南笙
南笙 2020-12-01 03:42

I have some code that saves a ticket in our system. If there is an error it does a RedirectToAction. The problem is that I don\'t seem to have my errors in the new action.

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 04:21

    I know this thread is old, but this blog about ASP.NET Best Practices has some excellent suggestions.
    #13 on the page deals with using 2 Action filters to save and restore ModelState between redirects.

    This is the pattern that my work uses, and I love it.

    Here's the simplified example:

    [ImportModelStateFromTempData]
    public ActionResult Dashboard()
    {
        return View();
    }
    
    [AcceptVerbs(HttpVerbs.Post), ExportModelStateToTempData]
    public ActionResult Dashboard(string data)
    {
        if (ValidateData(data))
        {
            try
            {
                _service.Submit(data);
            }
            catch (Exception e)
            {
                ModelState.AddModelError(ModelStateException, e);
            }
        }
    
        return RedirectToAction("Dashboard");
    }
    

提交回复
热议问题