I wrote an application using the ASP.NET MVC 5 framework. I use two-way binding between views and ViewModels.
Since I use two-way binding, I get the advantage of client and server side validation, which is cool. However, when I send a POST request to the server and the request handler throws an exception, I want to redirect the user to the GET method.
When a redirect occurs, I want to keep the model state so that the page looks the same when errors are displayed. I can save the state model and errors using ActionFilters and TempData using this approach . However, when the request is redirected, from POST to GET state of the model is saved as a System.Web.Mvc.ModelStateDictionary object, which is a key / value pair with all user inputs that come from the POST request.
To properly present the page to the end user, I need to bind the data in System.Web.Mvc.ModelStateDictionary to my own presentation model.
How to associate a System.Web.Mvc.ModelStateDictionary object with my presentation object?
This is what my code looks like
[ImportModelStateFromTempData] public ActionResult show(int id) { var prsenter = new UserProfileDetailsPresenter(id); ModelStateDictionary tmp = TempData["Support.ModelStateTempDataTransfer"]; if(tmp != null) { // Some how map tmp to prsenter } return View(prsenter); } [HttpPost] [ValidateAntiForgeryToken] [ExportModelStateToTempData] public ActionResult Update(int id, DetailsPresenter model) { try { if (ModelState.IsValid) { var updater = new UpdateAddressServiceProvider(CurrentUser); updater.Handle(model.General); } } catch (Exception exception) { ModelState.AddModelError("error", exception.Message); } finally { return new RedirectResult(Url.Action("Show", new { Id = id }) + "#General"); } }
source share