如何防止多次提交按鈕造成重復提交


項目中遇到這個問題,因為按鈕提交執行需要五到八秒,容易使用戶誤認為沒有提交成功,導致多次點擊按鈕提交,最后導致出錯。在網上找了下資料, 有的說不用服務器控件,或者自定義類,繼承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