Prevent Multiple Button Clicks

Posted by | December 10, 2011 | ASP.NET, Web Development | No Comments
images

Normally when a user clicks on a “Submit” button on a ASP.NET page, the button event will perform from code-behind a insert, update or delete operation. Once this is completed, the user will be redirect to another page. But if the database operation taken a long time to finish and the user hits the button once again, there be two requests submitted to the server.

I have looked around for solutions to prevent multiple button clicks. The best solution I came up was to use JavaScript to disable the button and replace it with a “please wait…” message. If the validation fails we show the button again and enable it.

 protected void Page_Load(object sender, EventArgs e)
{
	StringBuilder sb = new StringBuilder();
	sb.Append(@"if (typeof(Page_ClientValidate) == 'function'){
					if (Page_ClientValidate == false) {
						return false;
					}
				}

				this.value = 'Please wait...'; 
				this.disabled = true; ");

	sb.Append(this.Page.GetPostBackEventReference(Button));
	sb.Append(";");
	Button.Attributes.Add("onclick", sb.ToString());
}
avatar

About Farid

Creative web developer/designer, big fan of HTML5, CSS3 and client-side development. Software developer at Allegra Strategies London.