網上查了很多方法,都不太好使,不如自己寫一個,思路就是把按鈕按下時用Javascript在客戶端把按鈕下一次的onclick事件改為return false; 這樣在服務器端頁面重新送回客戶端之前,再次點擊按鈕都不會Post到服務端。同時將按鈕的style改為一行字的樣子,光標也變成沙漏狀。當服務端頁面重新產生後Button又會回到初始狀態。該方法對於F5刷新還不能防范,只是簡單封閉了F5的按鍵,為了防止刷新時再次提交可以在頁面返回前將一些TextBox控件清空,這樣就可以判斷如果該TextBox為空則不再進行後續操作(如寫庫)。 主要是考慮在企業內網使用,不是為了防黑客,所以不是非常嚴格。
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>禁止多次提交網頁測試</title>
<style type="text/css">
.disable
{
}{
border-style:none;
border-width: thin;
background-color:Transparent;
color: #CCCCCC;
cursor:wait;
}
</style>
<script type="text/javascript" language="javascript">
function DisableButton()
{
document.getElementById("Button2").className = "disable";
document.getElementById("Button2").value = '正在提交
.';
document.getElementById("Button2").onclick=Function("return false;");
return true;
}
document.onkeydown=mykeydown;
function mykeydown()
{
if(event.keyCode==116) //屏蔽F5刷新鍵 
{
window.event.keyCode=0;
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
輸入一些內容<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:ListBox ID="ListBox1" runat="server" Height="77px" Width="332px">
</asp:ListBox><br />
<asp:Button ID="Button2" runat="server" Text="OK" Width="77px"
onclick="Button2_Click" />
</div>
</form>
</body>
</html>
服務器端代碼,故意讓其延時等待3秒後再輸入,以模擬數據庫操作等慢速動作。
public partial class Default2 : System.Web.UI.Page

{
static public int count = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Button2.Attributes.Add("onclick", "return DisableButton();");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (TextBox1.Text != string.Empty)
{
System.Threading.Thread.Sleep(3000);
count++;
ListBox1.Items.Add(new ListItem("Hello "+TextBox1.Text + " 這是你第" + count.ToString() + "次點擊 " + DateTime.Now.ToString()));
TextBox1.Text = "";
}
}
}