Wednesday, June 04, 2008

Temporarily disable a button in ASP.NET

Sometimes you have a button that can trigger an asynchronous long-running process in which the http response is not a new page, but a file (excel/pdf etc).

You may want to disable the button such that impatient users don't unwittingly click the server resources into submission, but you want to re-enable it after the response is complete.

The bad news is, there is no way on the client-side to recognize when a new response has been sent (without ajax), but we can really easily set a timeout to re-enable the button after a fixed threshold of time.

Consider the following javascript function:
   function TemporarilyDisableButton(id, delay)
{
document.getElementById(id).disabled = true;
setTimeout("document.getElementById('"+id+"').disabled = false",delay);
}
The id is the ClientSideID of the button. The delay is the time in milliseconds to disable the button.
Wiring this together in your code behind is as simple as:
btnSumbit.Attributes.Add("onclick", "TemporarilyDisableButton('" + btnSumbit.ClientID + "',15000);" + GetPostBackEventReference(btnSumbit).ToString());
And the above code will disable the button for 15 seconds on the client side after the click event has fired.

0 Comments:

Post a Comment

<< Home