Detecting Refresh or Postback in ASP.NET

One of the biggest challenges for web developers is the resubmission of form data or the refresh of a form to post information to a database. This happens when the user, for whatever reason, resubmits or refreshes the form, which has the potential to cause chaos with duplicated database insertions or repeated email submissions.
In this article I Will show you how to define page is postback or refresh after postback.
Here my simple code

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["PostID"] = "1001";
            ViewState["PostID"] = Session["PostID"].ToString();
            Response.Write("First Load");
        }
        else
        {
            if (ViewState["PostID"].ToString() == Session["PostID"].ToString())
            {
                
                Session["PostID"] = (Convert.ToInt16(Session["PostID"]) + 1).ToString();

                ViewState["PostID"] = Session["PostID"].ToString();
                Response.Write("Postback");

            }
            else
            {
                ViewState["PostID"] = Session["PostID"].ToString();
                Response.Write("refreshed");

            }
        }
    }

Thanks

8 responses to “Detecting Refresh or Postback in ASP.NET”

  1. Hi,

    Send me sample code,screen shots to insert,delete,update,search,edit the data from the gridview jquery modal popup using asp.net

  2. Hi,

    This solution works fine in normal scenario but fails when press enter in address bar.

    It than shows “first load” and after that “refreshed” even on postback

    • when you press enter in address bar on postback… it not submit page postback data again means its load first time.

      We use this method to stop people to submit again on postback page.

Leave a Reply