Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect page refresh in .net

Tags:

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?

like image 636
Srikanth Avatar asked Aug 03 '12 10:08

Srikanth


People also ask

How to detect page refresh in asp net?

In the 'page_Load' event we check if the hidden field value is same as the old value. In case the value is not same that means it's a 'postback' and if the value is same then its 'refresh'. As per situation we set the 'httpContent. Items["Refresh"]' value.

How do I know if a website is refreshed or not?

A better way to know that the page is actually reloaded is to use the navigator object that is supported by most modern browsers. It uses the Navigation Timing API. thanks buddy this is accurate solution to detect either the page is reloaded from right click/refresh from the browser or reloaded by the url.

How can I tell if jquery is refreshing a page?

On Refresh/Reload/F5: If user will refresh the page, first window. onbeforeunload will fire with IsRefresh value = "Close" and then window. onload will fire with IsRefresh value = "Load", so now you can determine at last that your page is refreshing.


1 Answers

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();
}   
like image 196
lathomas64 Avatar answered Oct 23 '22 04:10

lathomas64