Tuesday, May 18, 2010

ASP.NET: How to prevent Duplicate Record Insertion on Page Refresh

This is a common problem in any web based application. Certainly, many developers might have banged their heads to solve "How do I prevent previously submitted form data from being reinserted into the database when the user presses the browser's Refresh/F5 buttons?"

The purpose of this article is to prevent the data from being reinserted into the database in a simple way when the browser's Refresh button is pressed.

Due to the nature of web pages and posted data, the form values are still held by the browser. A refresh of the page will post the data again and the data will wind up in your database an additional time.
This has nothing to do with ASP.NET in particular; it is a built-in browser behavior. The same thing can happen with PHP, ASP, and any other type of web page.

On goggling, perhaps you will get many suggestions to prevent this:
  1. Clear the caching of the page after the Action
  2. Disable the IE Refresh and F5 buttons.Etc… many more …..
Above solutions are purely depends on your requirement and involved a coding overhead.

Here is simplest and great solution that worked for me like a gem.
Add the following piece of code after your Database action.

Response.Redirect(Request.Url.ToString(), False)

Above technique simply redirect your page to the same page which could technically prevent the re-posting the previous action on Refresh.

Using Request.Url.ToString() as the first parameter of Response.Redirect will cause both the URL and the page's Querystring to be included in the redirect. The use of false as the second parameter will suppress the automatic Response.End that may otherwise generate a ThreadAbortedException.

NOTE: The only disadvantage of this approach is that any ViewState that had been built up will be lost.

No comments:

Post a Comment