Disable button on post back

Often post backs can take some time, and it appears to a user as if the browser is not responding causing the user to click the button multiple times.

In ASP.NET it is most simple to disable a button on click, and still post back to the page.
Here is how we can do this with an ASP.NET button.

First we'll create some Javascript to disable the button, but still call it's post back reference.
WE have to do this because once we disable a button, it stops the post back from occurring,
Let's create a button and take advantage of its OnClientClick property.
This property calls client side code before the page posts back.


asp:Button ID="btnDoSomething" runat="server" Text="Go" OnClick="btnDoSomething_Click" OnClientClick="disableAndPost()"/>

Now we can create a javascript block on the page to disable this button yet still call it's post back.
I'm going to use a Javascript and Inline C# script to accomplish this, but there are many ways you can do it.
I use inline script to retrieve the button's ID which is generated at runtime by ASP.NET, as well as call it's post back event reference.


script language="javascript" type="text/javascript">
   function disableAndPost()
      <%= ClientScript.GetPostBackEventReference(btnDoSomething,
"") %>;
'<%=btnDoSomething.ClientID %>').disabled="disabled";

Our first line calls the buttons post back event reference, the second line disables the button preventing it from being clicked again.

A nice added extra is once the page reloads, the button is no longer disabled as ASP.NET re-renders the page unaware of the client side property added to the button.

The next step would be to show a loading message or graphic during post back.

posted @ Tuesday, September 02, 2008 7:22 AM