如何防止多次提交按钮造成重复提交


项目中遇到这个问题,因为按钮提交执行需要五到八秒,容易使用户误认为没有提交成功,导致多次点击按钮提交,最后导致出错。在网上找了下资料, 有的说不用服务器控件,或者自定义类,继承Button基类等等其他方法,终于找到了如下比较简单的解决方法。演示代码如下:

前台aspx页面

<% @ Page Language = " C# "  AutoEventWireup = " true "  CodeBehind = " Default.aspx.cs "  Inherits = " buttonsubmit._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 >无标题页 </ title >
     < script    language ="javascript"  type ="text/javascript" >  
        
function    abc(object1) 
        { 
           
object1.disabled=true;          // 变灰 
            __doPostBack(object1.name , "" );      // 执行服务器端button1的click事件  这里特别要注意是
object1.name 而不能是 object1.id, 因为页面可能含有母版页
        } 
     
</ script > 
</ head >
< body >
     < form  id ="form1"  runat ="server" >
     < div >
        < asp:TextBox   id = "TextBox1"  style = "Z-INDEX:101;LEFT:8px;POSITION:absolute;TOP:8px "  runat = "server" >1 </ asp:TextBox > 
        < asp:Button   id = "Button1"  
            style
= "Z-INDEX:102;LEFT:8px;POSITION:absolute;TOP:40px "  runat = "server"  
            Text
="Button"  onclick ="Button1_Click" ></ asp:Button > 
     </ div >
     </ form >
</ body >
</ html >

 后台cs文件:

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;

namespace buttonsubmit
{
     public  partial  class _Default : System.Web.UI.Page
    {
         protected  void Page_Load( object sender, EventArgs e)
        {
             //    在此处放置用户代码以初始化页面 
            Page.ClientScript.GetPostBackEventReference(Button1,null);      // 这句很关键,有这句才能让客户端执行服务器端事件。 
            Button1.Attributes.Add( " onclick "" abc(this); ");  
        }

         protected  void Button1_Click( object sender, EventArgs e)
        {
             int k =  0;
             for ( int i =  0; i <  99999; i++)
            {
                 for ( int j =  0; j <  9999; j++)
                    k =  9;
            }
             this.TextBox1.Text =  " 2 "
        }
    }
}

 需要说明的是刷新页面是否会造成重复提交没有去试验,有兴趣和时间的朋友可以研究一下。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM