Asp.net
表單送出時禁用按鈕
我有一個按鈕,我想在表單送出時禁用它以防止使用者多次送出。
我曾嘗試使用 javascript onclick 天真地禁用該按鈕,但是如果客戶端驗證失敗,則該按鈕仍然被禁用。
當表單成功送出時,我如何禁用按鈕,而不僅僅是在使用者點擊時?
這是一個 ASP.NET 表單,所以如果可能的話,我想很好地與 asp.net ajax 頁面生命週期掛鉤。
試一試:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Threading; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Identify button as a "disabled-when-clicked" button... WebHelpers.DisableButtonOnClick( buttonTest, "showPleaseWait" ); } protected void buttonTest_Click( object sender, EventArgs e ) { // Emulate a server-side process to demo the disabled button during // postback. Thread.Sleep( 5000 ); } } using System; using System.Web; using System.Web.UI.WebControls; using System.Text; public class WebHelpers { // // Disable button with no secondary JavaScript function call. // public static void DisableButtonOnClick( Button ButtonControl ) { DisableButtonOnClick( ButtonControl, string.Empty ); } // // Disable button with a JavaScript function call. // public static void DisableButtonOnClick( Button ButtonControl, string ClientFunction ) { StringBuilder sb = new StringBuilder( 128 ); // If the page has ASP.NET validators on it, this code ensures the // page validates before continuing. sb.Append( "if ( typeof( Page_ClientValidate ) == 'function' ) { " ); sb.Append( "if ( ! Page_ClientValidate() ) { return false; } } " ); // Disable this button. sb.Append( "this.disabled = true;" ); // If a secondary JavaScript function has been provided, and if it can be found, // call it. Note the name of the JavaScript function to call should be passed without // parens. if ( ! String.IsNullOrEmpty( ClientFunction ) ) { sb.AppendFormat( "if ( typeof( {0} ) == 'function' ) {{ {0}() }};", ClientFunction ); } // GetPostBackEventReference() obtains a reference to a client-side script function // that causes the server to post back to the page (ie this causes the server-side part // of the "click" to be performed). sb.Append( ButtonControl.Page.ClientScript.GetPostBackEventReference( ButtonControl ) + ";" ); // Add the JavaScript created a code to be executed when the button is clicked. ButtonControl.Attributes.Add( "onclick", sb.ToString() ); } }
我不喜歡在程式碼隱藏中編寫所有這些 javascript。這是我的最終解決方案的樣子。
按鈕:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="doSubmit(this)" />Javascript:
<script type="text/javascript"><!-- function doSubmit(btnSubmit) { if (typeof(Page_ClientValidate) == 'function' && Page_ClientValidate() == false) { return false; } btnSubmit.disabled = 'disabled'; btnSubmit.value = 'Processing. This may take several minutes...'; <%= ClientScript.GetPostBackEventReference(btnSubmit, string.Empty) %>; } //--> </script>