方案一 原理:页面重新定向 适用范围:少量的页面事件处理,对页面的性能要求不是过高. 实现: BLL.ADD(MODEL); Response.Redirect(Request.RawUrl.ToString());//防止刷新后自动新增 方案二 原理:HttpModule(不懂) 首先编写如下类放入App_Code using System; using System.Web; using System.Collections; ///
/// NoRepeatOperModule 的摘要描述 /// public class NoRepeatOperModule : IHttpModule { //public NoRepeatOperModule() //{ // // // // TODO: 在此加入建構函式的程式碼 // // //} ///
/// 保存访问的页面记录,以页面路径为key, 标号为value /// static Hashtable historyRequest = null; ///
/// 请求路径 /// private string RequestPath { get { return HttpContext.Current.Request.Path; } } #region IHttpModule 成员 public void Dispose() { //throw new Exception("The method or operation is not implemented."); } public void Init(HttpApplication context) { if (historyRequest == null) { historyRequest = new Hashtable(); } context.BeginRequest += delegate(object sender, EventArgs e) { int lastTicket = GetLastTicket(); int currentTicket = GetCurrentTicket(lastTicket); // 比较当前标号和上一个的标号,判断页面请求是否来源于刷新操作 // 当前标号大于上一个标号 或初次请求都属于新的页面 if (currentTicket > lastTicket || (lastTicket == currentTicket && currentTicket == 0)) { // 标记并保存页面请求是否来源于刷新的bool值 HttpContext.Current.Items[RequestPath + "_IsRefreshed"] = false; historyRequest[RequestPath] = currentTicket; } else { HttpContext.Current.Items[RequestPath + "_IsRefreshed"] = true; } }; } #endregion /**/ ///
/// 获取某页面的上一个标号 /// ///
private int GetLastTicket() { if (!historyRequest.ContainsKey(RequestPath)) { return 0; } return int.Parse(historyRequest[RequestPath].ToString()); } /**/ ///
/// 获取页面的当前标号 /// ///
上一个标号 ///
private int GetCurrentTicket(int lastTicket) { int ticket; // CurrentTicket 为页面的隐藏域的内容 string currentTicket = HttpContext.Current.Request["CurrentTicket"]; if (currentTicket == null) { ticket = lastTicket; } else { ticket = int.Parse(currentTicket); } // 保存页面的下一个标号 HttpContext.Current.Items[RequestPath + "_NextTicket"] = ticket + 1; return ticket; } } 第二步:在BasePage中写 #region IsRefreshed ///
/// IsRefreshed /// public bool IsRefreshed { get { string requestPath = HttpContext.Current.Request.Path; return (bool)HttpContext.Current.Items[requestPath + "_IsRefreshed"]; } } #endregion /// /// 重写OnPreRenderComplete,生成隐藏域CurrentTicket /// /// protected override void OnPreRenderComplete(EventArgs e) { base.OnPreRenderComplete(e); string requestPath = HttpContext.Current.Request.Path; int ticket = int.Parse(HttpContext.Current.Items[requestPath + "_NextTicket"].ToString()); ClientScript.RegisterHiddenField("CurrentTicket", ticket.ToString()); } 第三步:webconfig配置
到此就大功告成了.每个继承BasePage的页面都可以直接使用. 范例: if (!IsRefreshed) { //不是新增 }
C#解决页面刷新后重新执行
最新推荐文章于 2023-09-18 19:24:14 发布