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?
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?
Another way to check page refresh. I have written custom code without java script or any client side.
Not sure, it's the best way but I feel good work around.
This article could be of help to you http://www.codeproject.com/Articles/68371/Detecting-Refresh-or-Postback-in-ASP-NET
you are adding a Guid to your view state to uniquely identify each page. This mechanism works fine when you are in the Page class itself. If you need to identify requests before you reach the page handler, you need to use a different mechanism (since view state is not yet restored).
The Page.LoadComplete event is a reasonable place to check if a Guid is associated with the page, and if not, create one.
check this http://shawpnendu.blogspot.in/2009/12/how-to-detect-page-refresh-using-aspnet.html
using the viewstate worked a lot better for me as detailed here. Basically:
If you want to detect a refresh on an HTTP GET rather than only POSTs, here's a hacky work-around that, in modern browsers, mostly works.
Javascript:
C#:
When the page loads, it will change add a QueryString parameter of
loaded=1
without reloading the page (again, this--window.history.replaceState
--only works in post-archaic browsers). Then, when the user refreshes the page, the server can check for the presence of theloaded
parameter of the query string.Caveat: mostly works
The case where this doesn't work is when the user clicks the Address Bar and presses enter. That is, the server will produce a false-positive, detecting a refresh, when odds are, the user actually meant to reload the page fresh.
Depending on your purposes, maybe this is desirable, but as a user, it would drive me crazy if I expected it to reset the page.
I haven't put too much thought into it, but it might be possible to write some magic in order to distinguish a refresh from a reset via the address bar using any/all of:
SessionState
(assumingSessionState
is enabled) and the value of theloaded
QueryString parameterwindow.onbeforeunload
event listenerloaded
QueryString parameter--though this would have a false-negative for clicking the browser's refresh button)If someone does come up with a solution, I'd love to hear it.