Any way to restore a model passed to a POST action when inside an OnException (ExceptionContext filterContext)?

The situation is as follows:

I cannot find a way to get the viewModel that was passed to the POST action method.

 [HttpPost] public ActionResult Edit(SomeCoolModel viewModel) { // Some Exception happens here during the action execution... } 

Inside the overridden OnException for the controller:

 protected override void OnException(ExceptionContext filterContext) { ... filterContext.Result = new ViewResult { ViewName = filterContext.RouteData.Values["action"].ToString(), TempData = filterContext.Controller.TempData, ViewData = filterContext.Controller.ViewData }; } 

When the code debugging filterContext.Controller.ViewData is null , because an exception occurred during the execution of the code and no view was received.

In any case, I see that filterContext.Controller.ViewData.ModelState full and has all the values ​​I need, but I do not have the full object ViewData => viewModel .: (

I want to return the same View with the published data/ViewModel back to the user at the center point. I hope you get my drift.

Is there any other way that I can follow to achieve the goal?

+6
source share
1 answer

You can create a custom TempData that inherits from DefaultModelBinder and assign models to TempData :

 public class MyCustomerBinder : DefaultModelBinder { protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) { base.OnModelUpdated(controllerContext, bindingContext); controllerContext.Controller.TempData["model"] = bindingContext.Model; } } 

and register it in Global.asax :

 ModelBinders.Binders.DefaultBinder = new MyCustomerBinder(); 

then follow these steps:

 protected override void OnException(ExceptionContext filterContext) { var model = filterContext.Controller.TempData["model"]; ... } 
+7
source

Source: https://habr.com/ru/post/973577/


All Articles