Tuesday, May 11, 2010

Preventing Multiple Form Submits In ASP.NET

Last year when I started working on the GridRoom Web site I spent some time researching the current best-practices for preventing multiple form submits in ASP.NET. (It was the first site I'd built from scratch using .NET, and I wasn't particularly fond of the architecture of existing .NET sites I had worked on.)

There are many options for preventing multiple submits, some of them quite complex and convoluted. But for most sites where the goal is simply to prevent users from accidentally clicking a submit button more than once the solution is very simple. Just override the OnLoad() method of your master page like this:

   1: protected override void OnLoad(EventArgs e)
   2: {
   3:     base.OnLoad(e);
   5:     // prevents form from being submitted multiple times in MOST cases
   6:     // programatic client-side calls to __doPostBack() can bypass this
   7:     Page.ClientScript.RegisterOnSubmitStatement(GetType(), "ServerForm",
   8:                                                 "if (this.submitted) return false; this.submitted = true; return true;");
   9: }

This registers a script block with the client-side form's OnSubmit event that prevents the form from being submitted multiple times, regardless of how many times the user clicks (or how many submit buttons are on the form).

This solution does not prevent users from intentionally submitting the same form multiple times. (This could be done programmatically, by refreshing the post-submit page, or by hitting the back button and resubmitting.)

You'll need to handle intentional re-submits on a case-by-case basis in your business logic. But if you're looking for a very simple solution that simply prevents inexperienced users from being confused by unexpected errors or duplicate data this will do the trick.


Anonymous said...

Very helpful Post. Thanks.

Harish said...

Awesome post! thanks i have wasted 2 hrs trying to find how to disable asp.net button when form submit...you are a savior

Header photo courtesy of: http://www.flickr.com/photos/tmartin/ / CC BY-NC 2.0