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,
"") %>;
      document.getElementById(
'<%=btnDoSomething.ClientID %>').disabled="disabled";
   }
-->
</script>

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

Print

Comments on this entry:

# re: Disable button on post back

Left by thanks at 12/12/2008 9:09 PM
Gravatar
Hey, thanks for the comment.

This was the simplest and working solution that satisfied my research abot how disable and do post back of a web control on c#

# re: Disable button on post back

Left by Jorge (Mexico) at 3/6/2009 9:34 PM
Gravatar
Hey,

its simple and easy to implement

I will use on my pages

Muchas Gracias

Your comment:



 (will not be displayed)


 
 
 
Please add 3 and 2 and type the answer here:
 

Live Comment Preview:

 
«March»
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910