如何在.net中检测页面刷新 [英] How to detect page refresh in .net
问题描述
我有一个 Button_click
事件.刷新页面时,先前的 Postback
事件再次触发.如何识别页面刷新事件以防止 Postback
操作?
I have a Button_click
event. While refreshing the page the previous Postback
event is triggering again. How do I identify the page refresh event to prevent the Postback
action?
我尝试了下面的代码来解决它.实际上,我在 SharePoint 页面中添加了一个可视化 webpart.添加 webpart 是一个回发事件,因此每次我将 webpart 添加到页面时 !postback 始终为 false,并且我在 else 循环中遇到错误,因为对象引用为 null
.
I tried the below code to solve it. Actually, I am adding a visual webpart in a SharePoint page. Adding webpart is a post back event so !postback is always false each time I'm adding the webpart to page, and I'm getting an error at the else loop because the object reference is null
.
if (!IsPostBack){
ViewState["postids"] = System.Guid.NewGuid().ToString();
Cache["postid"] = ViewState["postids"].ToString();
}
else{
if (ViewState["postids"].ToString() != Cache["postid"].ToString()){
IsPageRefresh = true;
}
Cache["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Cache["postid"].ToString();
}
我该如何解决这个问题?
How do I solve this problem?
推荐答案
使用 viewstate 对我来说效果更好,详细说明 此处.基本上:
using the viewstate worked a lot better for me as detailed here. Basically:
bool IsPageRefresh = false;
//this section of code checks if the page postback is due to genuine submit by user or by pressing "refresh"
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
IsPageRefresh = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
这篇关于如何在.net中检测页面刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!