Monday 1 June 2015

Detecting Page Refresh in ASP.Net


Detecting Page Refresh in ASP.Net

There are certain Scenario when we want to detect whether the page was refreshed or not. Or, Whether It was a Postback or a F5 Refresh.. The following Code Snippet will help you out to resolve this Issue..

Design Part:



 <asp:Label ID="Label1" runat="server"></asp:Label>
 
    <asp:Button ID="Button1" runat="server" Text="Do postback at server side"
        onclick="Button1_Click" />


Coding:


private bool IsPageRefresh = false;
        public bool IsPageRefresh1
        {
            get { return IsPageRefresh; }
            set { IsPageRefresh = value; }
        }
 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ViewState["postids"] = System.Guid.NewGuid().ToString();
                Session["postid"] = ViewState["postids"].ToString();
            }
            else
            {
                if (ViewState["postids"].ToString() != Session["postid"].ToString())
                {
                    IsPageRefresh = true;
                }
                else
                {
                    IsPageRefresh = false;
                }
                Session["postid"] = System.Guid.NewGuid().ToString();
                ViewState["postids"] = Session["postid"].ToString();
            }
        }
 
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (!IsPageRefresh1)
            {
                Label1.Text = "Page do normal postback";
            }
            else
            {
                Label1.Text = "Page refresh";
            }
        }

Now Check the Output by pressing F5 Key and by clicking the Button..

1 comment:

Thank You for Your Comments. We will get back to you soon.

back to top