Change ASP.NET MVC 2 ActionResult on an HTTP message

I want to do some attribute processing before returning the view. If I set appModel.Markup returned in the HttpPost ActionResult method below to “change”, it still says “original” on the form. Why can't I change my attribute in the HttpGet ActionResult method?

[HttpGet] public ActionResult Index() { return View(new MyModel { Markup = "original" }); } [HttpPost] public ActionResult Index(MyModel appModel) { return View(new MyModel { Markup = "modified" }); } 
+4
source share
1 answer

Because the "original" is stored in ModelState. When form values ​​are collected on the MVC side, they are stored in the ModelState . You used the used Html.TextBox helper. When you recreate the view after POST, it first looks at ModelState, and if there is a value, it sets that value. The value in the model object is no longer taken into account.

One solution is to follow the POST-REDIRECT-GET pattern. First POST, do something with the data, and then redirect:

 [HttpPost] public ActionResult Index(MyModel appModel) { //do something with data return RedirectToAction("Index"); } 

If you want to pass something between redirects, you can use TempData :

 [HttpPost] public ActionResult Index(MyModel appModel) { //do something with data TempData["Something"] = "Hello"; return RedirectToAction("Index"); } [HttpGet] public ActionResult Index() { var something = TempData["Something"]; //after redirection it contains "Hello" } 

After the redirect, ModelState does not work, so the value is not overridden. The POST-REDIRECT-GET template also helps to get rid of the effect of reponing the form when you press F5 in the browser.

+4
source

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


All Articles