Page 1 of 1

Calling C# event in Javascript

#1 marinus   User is offline

  • D.I.C Addict
  • member icon

Reputation: 138
  • View blog
  • Posts: 575
  • Joined: 14-April 10

Posted 22 February 2011 - 01:01 PM

One day i got a problem building a registration page with a
massive process running in C# code behind after clicking a button.

What i needed to do was disable the button when
the user clicks the button.
So that the user cant double click the button and mess up the

The Registration took about 20 seconds to complete which was a major problem because
people testing it regularly double clicked the button destroying the registration process.

What I tried

What happens was when I tried to disabled my button after click in Javascript with the OnClientClick
event the C# onclick event wouldn't fire of the button.

When the button is disabled in Javascript it does not run the server side code
so i needed a way to call the server side event.

My solution was as follows:

in C# code behind in Page_Load Event I put:


What the parameters means is as follows

btnRegister is my button ID.
"onclick" is the serverside event that you want to fire with __doPostBack in Javascript.

The button code is as follows:

 <asp:Button runat="server" ID="btnRegister"  onclick="btnRegister_Click" 
     Text="Book" Width="97px" OnClientClick="disableButton(this);" />

This is the Javascript to disable the button and activates Server Side button click

<script type="text/javascript">
         function disableButton(btn) {
            btn.value = 'Processing...';
            btn.disabled = 'disabled';
            __doPostBack("btnRegister", "onclick");

             /*Notice that i can access the onclick event from the server side in Javascript now
             thanks to Page.ClientScript.GetPostBackEventReference(btnRegister,"onclick");
              with the __doPostBack that activates the button click event.*/ 

To enable button after post-back you can put in this code

<script type="text/javascript">
         function SetSelection() {
          var btn = document.getElementById("btnRegister");
             if (btn.disabled == true) {
               btn.disabled = false;

and run it with

<body onload="SetSelection();">

It looks easy but it took two days for me to find the solution.



Is This A Good Question/Topic? 1
  • +

Page 1 of 1