How can I maintain ModelState with RedirectToAction?

前端 未结 6 966
日久生厌
日久生厌 2020-12-02 05:57

How can I return the result of a different action or move the user to a different action if there is an error in my ModelState without losing my ModelState information?

6条回答
  •  借酒劲吻你
    2020-12-02 06:54

    Store your view data in TempData and retrieve it from there in your Index action, if it exists.

       ...
       if (!ModelState.IsValid)
           TempData["ViewData"] = ViewData;
    
       RedirectToAction( "Index" );
    }
    
     public ActionResult Index()
     {
         if (TempData["ViewData"] != null)
         {
             ViewData = (ViewDataDictionary)TempData["ViewData"];
         }
    
         ...
     }
    

    [EDIT] I checked the on-line source for MVC and it appears that the ViewData in the Controller is settable, so it is probably easiest just to transfer all of the ViewData, including the ModelState, to the Index action.

提交回复
热议问题