Monday, May 7, 2012

Disable Button On PostBack (ASP.NET) - also works with validation controls

How many times have you seen the problem where somebody clicks on the Submit button a hundred times?  One technique to avoid multiple submissions is to use client side script to disable the button after it has been clicked.  Problem is you only want to disable the button if the form is valid and is actually going to PostBack.  To get around this call the client side function Page_ClientValidate() to see if the page is valid.  If it is you can set a caption on the button, like “Please Wait...“, disable it, and invoke its click event,  like in the following code sample:
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());

No comments:

Post a Comment