ASP.Net中防止页面刷新重复提交的几种方法
展开全部
a.使用服务器端的 Response.Redirect("YourPage");
b.使用客户端脚本 <script language=javascript>location.href='yourPage';</script>
这两种方法的缺点是如果要保留页面数据不太方便,如果不用保留可以采用。 2、操作完毕设置一个Session,进入页面时判断这个Session是否为null,如果不是表示已经提交过了,但是缺点就是这个页面无法再提交了,必须在别的页面清空这个Session。3、是从网上搜索到的一种方案,学习并共享一下:
DetectRefresh.aspx =========================== <%@ Page Inherits="StevenBey.Web.UI.Page" %> <html> <head> <title>Detecting Page Refresh [Demo]</title> </head> <body> <form runat="server"> <asp:button Text="Test Refresh" runat="server" /> </form> IsRefresh = <%= IsRefresh %> </body> </html> StevenBey.Web.UI.Page.cs ====================== namespace StevenBey.Web.UI { public class Page : System.Web.UI.Page { private bool _refreshState; private bool _isRefresh; public bool IsRefresh { get { return _isRefresh; } } protected override void LoadViewState(object savedState) { object[] allStates = (object[]) savedState; base.LoadViewState(allStates[0]); _refreshState = (bool) allStates[1]; if (Session["__ISREFRESH"]!=null){_isRefresh = _refreshState == (bool)Session["__ISREFRESH"]; }
} protected override object SaveViewState() { Session["__ISREFRESH"] = _refreshState; object[] allStates = new object[2]; allStates[0] = base.SaveViewState(); allStates[1] = !_refreshState; return allStates; } } } 4.此处提供的代码用来实现当asp.net页面中的某个Button被点击后disable掉该页面中所有的Button,从而防止提交延时导致的多次提交。基于之前的onceclickbutton脚本. <script language="javascript"><!--function disableOtherSubmit()
{ var obj = event.srcElement;
var objs = document.getElementsByTagName_r('INPUT');
for(var i=0; i<objs.length; i++){if(objs[i].type.toLowerCase() == 'submit'){objs[i].disabled = true;}} }//--></script>public class PreventMultiClick : System.Web.UI.Page{protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.Button Button2;
protected System.Web.UI.WebControls.LinkButton LinkButton1;
protected System.Web.UI.WebControls.Button Button3;
private void Page_Load(object sender, System.EventArgs e){this.GetPostBackEventReference(this.Button3); //保证 __doPostBack(eventTarget, eventArgument) 正确注册
if(!IsPostBack){System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("if (typeof(Page_ClientValidate) == 'function') { if (Page_ClientValidate() == false) { return false; }}"); //保证验证函数的执行
sb.Append("if(window.confirm('are you sure?')==false) return false;"); //自定义客户端脚本
sb.Append("disableOtherSubmit();"); // disable所有submit按钮
sb.Append(this.GetPostBackEventReference(this.Button3)); //用__doPostBack来提交,保证按钮的服务器端click事件执行
sb.Append(";");
Button3.Attributes.Add("onclick",sb.ToString());}} #region Web Form Designer generated code
override protected void OnInit(EventArgs e){//// CODEGEN: This call is required by the ASP.NET Web Form Designer.//InitializeComponent();
base.OnInit(e);}/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询