How to detect page refresh in .net

Viewed 33733

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 Answers

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

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

     }

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;
    }
Related