65.9K
CodeProject 正在变化。 阅读更多。
Home

在触发服务器端事件之前在客户端禁用按钮

starIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

1.00/5 (2投票s)

2007年9月6日

CPOL
viewsIcon

33324

在服务器端事件触发之前禁用客户端按钮。

引言

很多时候需要在服务器端事件触发之前禁用客户端按钮。一个例子是在处理信用卡支付时,在处理信用卡详细信息(这是一项耗时的操作)之前必须禁用该按钮。这有时可能会显得无响应,因此,如果用户再次单击该按钮,则存在支付可能被处理两次的风险。

因此,为了避免这种情况,最佳做法是在用户单击按钮后禁用该按钮,并在处理完成后重新启用它。可以通过一个简单的 JavaScript 函数和一个属性来禁用按钮。但是,问题是使用 JavaScript 禁用按钮后,服务器端事件将不会触发。

我在 ASP.NET 2.0 中发现了一个很棒的功能来克服这个问题:ClientScript.GetPostBackEventReferenceClientScript.GetPostBackEventReference 的主要功能是返回一个字符串,该字符串可用于客户端事件以导致服务器端回发。 http://msdn2.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.getpostbackeventreference.aspx

使用代码

//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 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>
在服务器端事件触发之前禁用按钮 - CodeProject - 代码之家
© . All rights reserved.