C#解决页面刷新后重新执行

方案一 原理:页面重新定向 适用范围:少量的页面事件处理,对页面的性能要求不是过高. 实现: 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) { //不是新增 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值