Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Disabling button at client side before firing server side event

1.00/5 (2 votes)
6 Sep 2007CPOL 1  
Disabling a button at client side before firing a server side event.

Introduction

Many times it's required to disable a button at client side before firing a server side event. One example is while processing credit card payments, the button has to be disabled until the card details are processed which is a time consuming job. This may sometimes seem to be unresponsive, so if the user clicks the button once again, the risk is that payment may get processed twice.

So to avoid this, it's a best practice to disable the button at client side once the user clicks the button and re-enable it after the processing is complete. Disabling the button can be achieved through a simple JavaScript function and an attribute. But the problem is the server side event doesn't get fired once the button is disabled using JavaScript.

I found a cool feature to overcome this in ASP.NET 2.0: ClientScript.GetPostBackEventReference. The main function of ClientScript.GetPostBackEventReference is that it returns a string that can be used in a client event to cause postback to the server. http://msdn2.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.getpostbackeventreference.aspx.

Using the code

C#
//Code Behind
//Add this within the Page_Load()
btnClick.Attributes.Add("onclick", 
   ClientScript.GetPostBackEventReference(btnClick, "") + 
   ";this.value='Processing Credit Card Payment...';this.disabled = true;"); 
 
//The actual code with which I tested
protected void Page_Load(object sender, EventArgs e)
{
    btnClick.Attributes.Add("onclick", 
      ClientScript.GetPostBackEventReference(btnClick, "") + 
      ";this.value='Processing Credit Card Payment...';this.disabled = true;");
}
protected void btnClick_Click(object sender, EventArgs e)
{
  System.Threading.Thread.Sleep(2000);
}
ASPX page
ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" 
   CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnClick" runat="server" Text="ClickMe" OnClick="btnClick_Click" />
</div>
</form>
</body>
</html>

<h2>
This would do the job perfectly!
</h2>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)