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

2008-07-17  来源: 博客园  浏览次数 8

网上查了很多方法,都不太好使,不如自己写一个,思路就是把按钮按下时用Javascript在客户端把按钮下一次的onclick事件改为return false; 这样在服务器端页面重新送回客户端之前,再次点击按钮都不会Post到服务端。同时将按钮的style改为一行字的样子,光标也变成沙漏状。当服务端页面重新产生后Button又会回到初始状态。该方法对于F5刷新还不能防范,为了防止刷新时再次提交可以在页面返回前将一些TextBox控件清空,这样就可以判断如果该TextBox为空则不再进行后续操作(如写库)。

 1<head runat="server">
 2    <title>禁止多次提交网页测试</title>
 3    <style type="text/css">
 4    .disable
 5    {
 6        border-style:none; 
 7        border-width: thin; 
 8        background-color:Transparent; 
 9        color: #CCCCCC; 
10        cursor:wait;
11    }

12    
</style>
13    <script type="text/javascript" language="javascript">
14    function DisableButton()
15    {
16        document.getElementById("Button2").className  = "disable";
17        document.getElementById("Button2").value = '正在提交.';
18        document.getElementById("Button2").onclick=Function("return false;");
19        return true;
20    }

21    
</script>
22</head>
23<body>
24    <form id="form1" runat="server">
25    <div>
26        输入一些内容<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
27        <br />
28        <asp:ListBox ID="ListBox1" runat="server" Height="77px" Width="332px">
29    </asp:ListBox><br />
30        <asp:Button ID="Button2" runat="server" Text="OK" Width="77px"
31            onclick="Button2_Click" />
32    </div>
33    
34    </form>
35</body>
36</html>


服务器端代码,故意让其延时等待3秒后再输入,以模拟数据库操作等慢速动作。

 1public partial class Default2 : System.Web.UI.Page
 2{
 3    static public int count = 0;
 4    protected void Page_Load(object sender, EventArgs e)
 5    {
 6        if (!IsPostBack)
 7        {
 8            Button2.Attributes.Add("onclick""return DisableButton();");
 9        }

10    }

11
12    protected void Button2_Click(object sender, EventArgs e)
13    {
14        if (TextBox1.Text != string.Empty)
15        {
16            System.Threading.Thread.Sleep(3000);
17            count++;
18            ListBox1.Items.Add(new ListItem("Hello "+TextBox1.Text + "  这是你第" + count.ToString() + "次点击   " + DateTime.Now.ToString()));
19            TextBox1.Text = "";
20        }

21    }

22}

相关主题:

网友评论