How to detect page refresh in asp.net

Page refresh is a one challenges that all web developers need to faces. It is because, when you have a button, and user click on the button and the process actually still processed at server side but the user refresh the page. The browser will ask user is either to resubmit or not. Normal user will always click resubmit. So the process actually repeat at server side also. This will cause a duplicate or redundant activity at server side which is will lead to incorrect result.

Follow this example to detect the page refresh in ASP.NET .

  1. Create sample page name DetectPageRefresh.aspx 
We will do logic to detect page refresh at the code behind.

The  DetectPageRefresh.aspx  Page

  <asp:Label ID="Label1" runat="server"></asp:Label>

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



The Code Behind

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



The output

  1. Click on the button.
  2. and then press F5 button to refresh page







By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

Popular posts from this blog

How to create zip file to download in JSP- Servlet

How to create DataGrid or GridView in JSP - Servlet

Pinging in ASP.NET Example