views:

48

answers:

1

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, so that they cannot just accidentally re-submit the data again.

How does one do this in ASP.NET MVC?

+1  A: 

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.

Ahmad
I've tried this before and it hasn't worked for me, but maybe I'm doing something wrong. Let me try again and get back to you.
Pretzel
@pretzel - any progress?
Ahmad
@Ahmad: Still no luck. I'll try to replicate what I'm doing in a test project (iow, strip out all the unnecessary code so I can show you what I'm doing.) I'll post back in a few days. Thanks for checking in on me! :)
Pretzel