开发者

ASP.Net MVC2 -- After posting, how to clear form if user hits Back button?

In my web app, after clicking the Submit button on an ASP.NET MVC form, the user is displayed either an Error screen or a Success screen. In the case of the Error, the user is instructed to click the Back button on the browser and fix whatever they didn't do right and try submitting again.

This works fine because when the user clicks back, all the previously entered data is still in the screen in the various fields. But in the case of the Success screen, I would like the data to be cleared if the user clicks Back, 开发者_StackOverflowso that they cannot just accidentally re-submit the data again.

How does one do this in ASP.NET MVC?


The way you can accomplish this is to use the Post-Get-Redirect pattern. It's not asp-mvc specific but as Wiki says it

a common design pattern for web developers to help avoid certain duplicate form submissions and allow user agents to behave more intuitively with bookmarks and the refresh button.

Clicking the back is not safe way to handle this. Some browsers don't maintain the form state after submission. This pattern directly address the accidentally re-submit data issue.

In terms of code, have a look at this blog post by Jag Reehal concerning how to unit test controllers.

[HttpPost]
public ActionResult Create(SomeViewModel model)
{
  if (ModelState.IsValid)
  {
     // do some stuff that saves your data and then...
     return RedirectToAction("Success");
  }
  else
  {
     // your model is not valid so return the form back to the user for 
     // additional modifications.
     return View(model);
  }   
}

Note: while the above uses ModelState for data validation, you may have your own set of validations and error checking routines which can also be used in this pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜