How to detect page refresh in .net

37.3k views Asked by At

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?

6

There are 6 answers

0
Rohan On

This worked fine for me..

bool isPageRefreshed = false;

protected void Page_Load(object sender, EventArgs args)
{
    if (!IsPostBack)
    {
        ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
        Session["SessionId"] = ViewState["ViewStateId"].ToString();
    }
    else
    {
        if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
        {
            isPageRefreshed = true;
        }

        Session["SessionId"] = System.Guid.NewGuid().ToString();
        ViewState["ViewStateId"] = Session["SessionId"].ToString();
    } 
}
1
Vinoth On

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

0
Narender Kumar On

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.

protected void Page_Load(object sender, EventArgs e)
    {
        if ((Boolean)Session["CheckRefresh"] is true)
        {
            Session["CheckRefresh"] = null;
            Response.Write("Page was refreshed");
        }
        else
        { }
    }
    protected void Page_PreInit(object sender, EventArgs e)
    {
        Session["CheckRefresh"] = Session["CheckRefresh"] is null ? false : true;
    }
0
dx_over_dt On

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:

window.onload = function () {
    // regex for finding "loaded" query string parameter
    var qsRegex = /^(\?|.+&)loaded=\d/ig;
    if (!qsRegex.test(location.search)) {
        var loc = window.location.href + (window.location.search.length ? '&' : '?') + 'loaded=1';
        window.history.replaceState(null, document.title, loc);
    }
};

C#:

public bool IsPageRefresh 
{
    get
    {
        return !string.IsNullOrEmpty(Request.QueryString["loaded"]);
    }
}

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 the loaded 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 (assuming SessionState is enabled) and the value of the loaded QueryString parameter
  • the window.onbeforeunload event listener
  • keyboard events (detecting F5 and Ctrl + R to quickly change the URL back to removing the loaded QueryString parameter--though this would have a false-negative for clicking the browser's refresh button)
  • cookies

If someone does come up with a solution, I'd love to hear it.

0
Yogi On

Simple Solution

Thought I'd post this simple 3 line solution in case it helps someone. On post the session and viewstate IsPageRefresh values will be equal, but they become out of sync on a page refresh. And that triggers a redirect which resets the page. You'll need to modify the redirect slightly if you want to keep query string parameters.

    protected void Page_Load(object sender, EventArgs e)
    {
        var id = "IsPageRefresh";
        if (IsPostBack && (Guid)ViewState[id] != (Guid)Session[id]) Response.Redirect(HttpContext.Current.Request.Url.AbsolutePath);
        Session[id] = ViewState[id] = Guid.NewGuid();

        // do something

     }
2
lathomas64 On

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();
}