我有一个Button_click事件.刷新页面时,以前的Postback事件将再次触发.如何识别页面刷新事件以防止Postback操作?
我试了下面的代码来解决它.实际上,我在SharePoint页面中添加了一个可视化的webpart.添加webpart是一个回发事件,所以!每次我将webpart添加到页面时,postback总是错误的,我在else循环中收到错误,因为对象引用是空的.
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(); }
如何解决这个问题?
解决方法
对于我来说,使用viewstate对于我来说比
here更好.基本上:
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(); }