您的位置:首页 > 编程语言 > ASP

防止ASP.NET按钮多次提交的办法

2009-04-10 15:17 453 查看
对“添加”、“提交”、“保存”、“更新”等按钮需要对数据库进行写操作的按钮,一定要在页面初始化时加载脚本,防止多次重复点击,例如:

protected void Page_Load(object sender, EventArgs e)
{
//.net 2.0以上
Button1.Attributes.Add("onclick", "this.disabled=true;" + this.ClientScript.GetPostBackEventReference(Button1, ""));
}


测试页面:

为了测试,我们可以建立一个页面,加入一个btnAdd按钮
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AddAndEditUser.aspx.cs" Inherits="AddUser" %><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>添加和编辑页面示例</title>
</head>
<body>
<form id="frmMain" runat="server">
<asp:Button ID="btnAdd" runat="server" CssClass="INPUT-BUTTON-Save" OnClick="btnAdd_Click">
</asp:Button>
</form>
</body>
</html>
/*----------------------------------------------------------------
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class AddUser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btnAdd.Attributes.Add("onclick", "this.disabled=true;" + this.ClientScript.GetPostBackEventReference(btnAdd, ""));

}
protected void btnAdd_Click(object sender, EventArgs e)
{
//模拟网络拥塞5秒钟
System.Threading.Thread.Sleep(5000);
}
}


还有可以用Javascript 在客户端把按钮下一次的onclick事件改为return false; 这样在服务器端页面重新送回客户端之前,再次点击按钮都不会Post到服务端。同时将按钮的style改为一行字的样子,光标也变成沙漏状。当服务端页面重新产生后Button又会回到初始状态。该方法对于F5刷新还不能防范,只是简单封闭了F5的按键,为了防止刷新时再次提交可以在页面返回前将一些TextBox控件清空,这样就可以判断如果该TextBox为空则不再进行后续操作(如写库)。 或是后台操作成功后跳转到另一个页面以防止恶意刷新。主要是考虑在企业内网使用,不是为了防黑客,所以不是非常严格。

《br/> <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>禁止多次提交网页测试</title>
<mce:style type="text/css"><!--
.disable
{
border-style:none;
border-width: thin;
background-color:Transparent;
color: #CCCCCC;
cursor:wait;
}

--></mce:style><style type="text/css" mce_bogus="1">            .disable
{
border-style:none;
border-width: thin;
background-color:Transparent;
color: #CCCCCC;
cursor:wait;
}
</style>
<mce: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;
}
}

// --></mce: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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: