防止在服务器处理完成之前用户多次点击提交按

提交表单时,如果网页速度过慢或者其他原因,用户多次提交能导致数据的修改,怎么解决这个问题呢,接下来将为您解决这个问题,需要的朋友可以了解下

如果网页速度过慢或者其他原因,用户多次提交能导致数据的修改,怎么解决这个问题呢?
这段是放在 Page_Load 中

复制代码 代码如下:


if(!Page.IsPostBack)
{
System.Text.StringBuilder s = new System.Text.StringBuilder();
s.Append("a();");
s.Append(this.GetPostBackEventReference(this.Button1));
this.Button1.Attributes.Add("onclick",s.ToString());
}
a() 是 JS
function a()
{
var ok=document.getElementById('Button1');
ok.disabled = true;
return true;
}


浓缩后即为

复制代码 代码如下:


btnSave.Attributes.Add("onclick","this.disabled='true';"+GetPostBackEventReference(btnSave));


一个问题稍微困扰了一下,后来解决了,btnSave.Attributes.Add("onclick","a();"+GetPostBackEventReference(btnSave)); 如果a()这个函数还包含其他验证,比如说一些正则验证等,btnSave.Attributes.Add("onclick","return a();"+GetPostBackEventReference(btnSave)); 则不能进行。可以将JS代码全部在CS文件中写就OK拉。

复制代码 代码如下:


System.Text.StringBuilder s = new System.Text.StringBuilder(); s.Append("var ok=document.getElementById('Button1'); ");
s.Append("ok.disabled = true; ");
s.Append(this.GetPostBackEventReference(this.Button1));
this.Button1.Attributes.Add("onclick",s.ToString());
//.net 2.0以上
Button1.Attributes.Add("onclick", "this.disabled=true;" + this.ClientScript.GetPostBackEventReference(Button1, ""));



复制代码 代码如下:


<asp:Button runat="server" UseSubmitBehavior="false" OnClientClick="this.value='Sumbit';this.disabled=true; " Text="Sumbit" />


其他的方法(可供尝试)
方法一

复制代码 代码如下:


protected void Page_Load(object sender, EventArgs e)
{
btn.Attributes.Add("onclick", "state=true;");
StringBuilder sb = new StringBuilder();
sb.Append("if (!state) return;");
sb.Append("var button=document.getElementByIdx_x('btn');");
sb.Append("button.value='Please Wait...';");
sb.Append("document.body.style.cursor='wait';");
sb.Append("button.disabled=true;");
string strScript = "<script>";
strScript = strScript + "var state=false;";
//将函数绑定到页面的onbeforeunload事件:
strScript = strScript + "window.attachEvent('onbeforeunload',function(){" + sb.ToString() + "});";
strScript = strScript + "</" + "script>";
Page.RegisterStartupScript("onbeforeunload", strScript);
}
protected void Submit_Click(object sender, EventArgs e)
{
//模拟长时间的按钮处理
System.Threading.Thread.Sleep(2000);
Response.Write("<script>alert('bbbbbb!!');" + "</" + "script>");
}
<asp:Button Text="Submit"
runat="server"/>


方法2

复制代码 代码如下:


<asp:button runat="server" OnClientClick="this.disabled=true;this.form.submit();" UseSubmitBehavior="False"/>


方法3

复制代码 代码如下:


this.btnSubmit.Attributes["onclick"]=this.GetPostBackEventReference(this.btnSubmit)+";this.disabled=true;";//防止重复提交

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjdfwf.html