How can I manually bind data from ModelStateDictionary to a view model using ASP.NET MVC?

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"); } } 
+5
source share
1 answer

If there is an error, do not redirect, just return the View.

 [HttpPost] [ValidateAntiForgeryToken] [ExportModelStateToTempData] public ActionResult Update(int id, DetailsPresenter model) { try { if (ModelState.IsValid) { var updater = new UpdateAddressServiceProvider(CurrentUser); updater.Handle(model.General); } return new RedirectResult(Url.Action("Show", new { Id = id }) + "#General"); } catch (Exception exception) { ModelState.AddModelError("error", exception.Message); // Return the named view directly, and pass in the model as it stands. return View("Show", model); } } 
+4
source

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


All Articles