A very common issue that we come across is duplicate insertion of data on refreshing the page. For instance, , we have a web page with some text boxes and a button which when clicked inserts data into the Database. Now if we have already inserted data and then refresh the page, the record is inserted in the Database once again.
So how do we identify if the page has been refreshed and then restrict it from reinsert the record ?
bool IsPageRefreshed = false; // Variable for Checking whether the Page got Refreshed or not. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // Set the Postback ID string postBackID = System.Guid.NewGuid().ToString(); ViewState["postBackID"] = postBackID; Session["postBackID"] = ViewState["postBackID"].ToString(); } else { string sessionPostBackID = Session["postBackID"].ToString(); string viewPostBackID = ViewState["postBackID"].ToString(); // If ViewState GUID is not equal to Session GUID, then Page has got Refreshed. if ( viewPostBackID != sessionPostBackID) { IsPageRefreshed = true; } // Set the Postback ID string postBackID = System.Guid.NewGuid().ToString(); ViewState["postBackID"] = postBackID; Session["postBackID"] = ViewState["postBackID"].ToString(); } } protected void Button1_Click(object sender, EventArgs e) { if (!IsPageRefreshed) { // Logic to Insert Record in DB. } else { // Do Nothing. } }