|
Back

Disabling a Button Onclick in ASP.net to Prevent Multiple Submits
This article shows you how to stop people multiple submitting forms in ASP.net. The code disables the button after it has been clicked. However it only does so if the form is valid and is actually going to PostBack ie if you have ASP.net validation on the page which catches a user on some empty fields or such like it will not disable the button.
System.Text.StringBuilder sbValid = new System.Text.StringBuilder();
sbValid.Append("if (typeof(Page_ClientValidate) == 'function') { ");
sbValid.Append("if (Page_ClientValidate() == false) { return false; }} ");
sbValid.Append("this.value = 'Please wait...';");
sbValid.Append("this.disabled = true;");
sbValid.Append("document.all.btnSubmit.disabled = true;");
//GetPostBackEventReference obtains a reference to a client-side script function that causes the server to post back to the page.
sbValid.Append(this.Page.GetPostBackEventReference(this.btnSubmit));
sbValid.Append(";");
this.btnSubmit.Attributes.Add("onclick", sbValid.ToString());
Note if you are using ASP.net 2 with master pages the master page functionality actually renames the button to something like ctl00$ContentPlaceHolder1$btnSubmit in which case you need to change line 6 to the line below:
sbValid.Append("document.all.ctl00$ContentPlaceHolder1$btnSubmit.disabled = true;");
Also remember to use using System.Text; at the top of your code behind so it can use the stringbuilder class.
Back
|