我有一个按钮,我想在表单提交时禁用它以防止用户多次提交。
我曾尝试使用 javascript onclick 天真地禁用该按钮,但是如果客户端验证失败,则该按钮仍然被禁用。
当表单成功提交时,我如何禁用按钮,而不仅仅是在用户单击时?
这是一个 ASP.NET 表单,所以如果可能的话,我想很好地与 asp.net ajax 页面生命周期挂钩。
我有一个按钮,我想在表单提交时禁用它以防止用户多次提交。
我曾尝试使用 javascript onclick 天真地禁用该按钮,但是如果客户端验证失败,则该按钮仍然被禁用。
当表单成功提交时,我如何禁用按钮,而不仅仅是在用户单击时?
这是一个 ASP.NET 表单,所以如果可能的话,我想很好地与 asp.net ajax 页面生命周期挂钩。
我不喜欢在代码隐藏中编写所有这些 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>
试一试:
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() );
}
}
以下功能很有用,不需要往往不可靠的禁用部分。只需使用“return check_submit();” 作为提交按钮的 onclick 处理程序的一部分。
还应该有一个隐藏字段来保存 form_submitted 初始值 0;
<input type="hidden" name="form_submitted" value="0">
function check_submit (){
if (document.Form1.form_submitted.value == 1){
alert("Don't submit twice. Please wait.");
return false;
}
else{
document.Form1.form_submitted.value = 1;
return true;
}
return false;
}
在提交处理程序的最后禁用按钮。如果验证失败,它应该在此之前返回 false。
但是,JavaScript 方法不是可以依赖的,因此您也应该有一些东西来检测服务器上的重复项。
如果验证成功,则禁用该按钮。如果不是,那就不要。
function validate(form) {
// perform validation here
if (isValid) {
form.mySubmitButton.disabled = true;
return true;
} else {
return false;
}
}
<form onsubmit="return validate(this);">...</form>
将按钮的可见性设置为“无”;
btnSubmit.Attributes("onClick") = document.getElementById('btnName').style.display = 'none';
它不仅可以防止重复提交,而且可以清楚地向用户表明您不想多次按下按钮。
不确定这是否有帮助,但表单中有 onsubmit 事件。每当表单提交(从任何按钮或控件)时,您都可以使用此事件。供参考:http ://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html
一个解决方案是在单击按钮时设置一个隐藏字段,编号为 1。
在按钮单击处理程序上,首先检查该数字是否不是 1,只是从函数中返回。
您还可以利用表单上可用的 onsubmit() javascript 事件。此事件在表单实际提交时触发,并且在验证完成之前不应捕获。
这是一种比rp建议的更简单但相似的方法:
function submit(button) {
Page_ClientValidate();
if(Page_IsValid)
{
button.disabled = true;
}
}
<asp:Button runat="server" ID="btnSubmit" OnClick="btnSubmit_OnClick" OnClientClick="submit(this)" Text="Submit Me" />
刚刚听说过 <asp:Button> 的“DisableOnSubmit”属性,如下所示:
<asp:Button ID="submit" runat="server" Text="Save"
OnClick="yourClickEvent" DisableOnSubmit="true" />
渲染时,按钮的 onclick 属性如下所示:
onclick="this.disabled=true; setTimeout('enableBack()', 3000);
WebForm_DoPostBackWithOptions(new
WebForm_PostBackOptions('yourControlsName', '', true, '', '', false, true))
“enableBack()” javascript 函数如下所示:
function enableBack()
{
document.getElementById('yourControlsName').disabled=false;
}
所以当按钮被点击时,它会被禁用 3 秒。如果表单成功发布,那么您永远不会看到重新启用按钮。但是,如果任何验证器失败,则该按钮会在 3 秒后再次启用。
所有这一切只需在按钮上设置一个属性——无需手动编写 JavaScript 代码。
请注意,如果您使用带有UseSubmitBehavior="false"
.
我使用 rp 代码的以下变体:
public static void DisableButtonOnClick(Button button, string clientFunction)
{
// If the page has ASP.NET validators on it, this code ensures the
// page validates before continuing.
string script = "if (typeof(Page_ClientValidate) == 'function') { "
+ "if (!Page_ClientValidate()) { return false; } } ";
// disable the button
script += "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))
script += string.Format("if (typeof({0}) == 'function') {{ {0}() }} ", clientFunction);
// only need to post back if button is using submit behaviour
if (button.UseSubmitBehavior)
script += button.Page.GetPostBackEventReference(button) + "; ";
button.Attributes.Add("onclick", script);
}
正确的(至少就用户友好性而言)方法是使用 OnClientClick 属性禁用按钮,执行客户端验证,然后使用结果来继续或重新启用按钮。
当然,您还应该为此编写服务器端代码,因为即使由于 JavaScript 的缺乏或特定实现,您也不能依赖验证。但是,如果您依赖服务器控制按钮的启用/禁用状态,那么您基本上无法阻止用户多次提交表单。出于这个原因,您应该有某种逻辑来检测同一用户在短时间内的多次提交(例如,来自同一会话的相同值)。
我的解决方案之一如下:
在您的 aspx 文件的 page_load 中添加脚本
HtmlGenericControl includeMyJava = new HtmlGenericControl("script");
includeMyJava.Attributes.Add("type", "text/javascript");
includeMyJava.InnerHtml = "\nfunction dsbButton(button) {";
includeMyJava.InnerHtml += "\nPage_ClientValidate();";
includeMyJava.InnerHtml += "\nif(Page_IsValid)";
includeMyJava.InnerHtml += "\n{";
includeMyJava.InnerHtml += "\nbutton.disabled = true;";
includeMyJava.InnerHtml += "}";
includeMyJava.InnerHtml += "\n}";
this.Page.Header.Controls.Add(includeMyJava);
然后将您的 aspx 按钮参数设置如下:
<asp:Button ID="send" runat="server" UseSubmitBehavior="false" OnClientClick="dsbButton(this);" Text="Send" OnClick="send_Click" />
请注意,“onClientClick”有助于禁用按钮,“UseSubmitBehaviour”禁用页面的传统提交行为,并允许asp.net在用户脚本上呈现提交行为。
祝你好运
- 瓦卡斯阿斯拉姆
因此,简单地通过 javascript 禁用按钮不是跨浏览器兼容的选项。如果您只使用 Chrome 将不会提交表单OnClientClick="this.disabled=true;"
以下是我在 Firefox 9、Internet Explorer 9 和 Chrome 16 中测试过的解决方案:
<script type="text/javascript">
var buttonToDisable;
function disableButton(sender)
{
buttonToDisable=sender;
setTimeout('if(Page_IsValid==true)buttonToDisable.disabled=true;', 10);
}
</script>
然后使用表单提交按钮的单击事件注册“disableButton”,一种方法是:
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClientClick="disableButton(this);" />
值得注意的是,如果客户端验证失败,这可以解决您禁用按钮的问题。也不需要服务器端处理。
在@rp. 的回答的基础上,我对其进行了修改以调用自定义函数,并在成功时提交和禁用,或者在错误时“停止”:
public static void DisableButtonOnClick(Button ButtonControl, string ClientFunction)
{
StringBuilder sb = new StringBuilder(128);
if (!String.IsNullOrEmpty(ClientFunction))
{
sb.AppendFormat("if (typeof({0}) == 'function') {{ if ({0}()) {{ {1}; this.disabled=true; return true; }} else {{ return false; }} }};", ClientFunction, ButtonControl.Page.ClientScript.GetPostBackEventReference(ButtonControl, null));
}
else
{
sb.Append("return true;");
}
ButtonControl.Attributes.Add("onclick", sb.ToString());
}
在我们的一个遗留应用程序中遇到了 rp 的代码,该应用程序正在与一些疯狂的行为作斗争。
将其追踪到一个奇怪的事件触发组合 - 当 DisableButtonOnClick() 在 UpdatePanel 内的 asp 按钮上使用时,POST 将被发送两次(一次由 DisableButtonOnClick() 添加的 doPostBack,一次由 UpdatePanel)。但是,这只发生在某些浏览器上(Edge 的早期版本,但不是最近的版本,IE11 做到了,Chrome 和 FireFox 没有(至少我测试的版本))。我认为 Chrome 和更新版本的 Edge 正在以某种方式在内部处理这种情况。在 IE 中使用 F12 devtools 跟踪问题 - 这两个 POST 发生得如此紧密,以至于第一个 POST 立即中止,但在某些情况下(网络延迟、用户机器负载等),请求确实在浏览器可以之前到达服务器中止。因此,这会导致整个系统中的按钮按下看似随机的双张贴,追溯起来很痛苦。解决方法是添加一个“return false;” 在 doPostBack 之后,以防止在较旧的浏览器运行时 UpdatePanel 参与其中。
TLDR - 请注意更新面板中按钮上的此代码。这是一个很好的方法和很好的方法,但在我(可能是边缘)的情况下有一个潜在的问题。
ps - 我会评论 rp 的帖子,但我没有代表。认为它可能对未来的旅行者有用。