Many a times it’s required to disable the button at client side before firing the server side event. One best 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 practise to disable the button at client side once the user clicks the button and reenable it after the processing is complete. Disabling the button can be achieved through 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
Code
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
<%@ 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>