防止在服务器处理完成之前用户多次点击提交按钮处理代码
如果网页速度过慢或者其他原因,用户多次提交能导致数据的修改,怎么解决这个问题呢?
这段是放在 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 ID="btnSumbit" runat="server" UseSubmitBehavior="false" OnClientClick="this.value='Sumbit';this.disabled=true; " Text="Sumbit" OnClick="btnSumbit_Click" />
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 ID="btn" Text="Submit" OnClick="Submit_Click"
runat="server"/>
<asp:button id="btnSubmit" OnClick="Submit_Click" runat="server" OnClientClick="this.disabled=true;this.form.submit();" UseSubmitBehavior="False"/>
this.btnSubmit.Attributes["onclick"]=this.GetPostBackEventReference(this.btnSubmit)+";this.disabled=true;";//防止重复提交