Jul 19, 2012

How to check if Page is refreshed in ASP.Net

In this post, i have posted the code to detect if page is refreshed in asp.net. But before that, i would like to share the scenario where it is required.

why there is need to detect if page refreshed in asp.net?.

Suppose you have a button "Save" on the page and on click of it, you are inserting a record in the database. Now if user click on Save, a record get inserted in the database but now if he/she refreshes the page, the Save Click event gets fire again and as a result same record get inserted again in the database. In order to handle this, we need to detect if page is refreshed, so that we can stop reinserting the record in the database.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageRefresh.aspx.cs" Inherits="PageRefresh" %>
<head runat="server">
    <form id="form1" runat="server">
        <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" />

using System;
using System.Web.UI;

public partial class PageRefresh : System.Web.UI.Page
    protected void Page_PreRender(object sender, EventArgs e)
        ViewState["IsPageRefreshed"] = Session["IsPageRefreshed"];

    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            Session["IsPageRefreshed"] = Server.UrlDecode(System.DateTime.Now.ToString());

    protected void btnSave_Click(object sender, EventArgs e)
        if (Session["IsPageRefreshed"].ToString() == ViewState["IsPageRefreshed"].ToString())
            Session["IsPageRefreshed"] = Server.UrlDecode(System.DateTime.Now.ToString());
            ScriptManager.RegisterClientScriptBlock(this, this.Page.GetType(), "abc", "alert('Save Clicked')", true);
            ScriptManager.RegisterClientScriptBlock(this, this.Page.GetType(), "abc", "alert('Page Refreshed')", true);

    Choose :
  • OR
  • To comment
Write Comments
  1. Don't you think. whenever you insert the record you should create some Id for that, than only you would reload the page with that id, if user wants to be on same page otherwise you should have to redirect it on other page after save action.

  2. Dear Jagat
    That can be done and also there can be more alternatives too. But in this post, i have just taken that scenario to detect if page is refreshed. Main motto of this post is to share - How to detect if page is refreshed?


Probabilmente come studente universitario ti troverai a scrivere una o più tesi per il tuo analogo esame di fine carriera. Ma di cosa si tratta in particolare? Scopriamo quali sono i pro dei tool per riscrivere testo che troverai online. Per strumento di parafrasi si intende un tool online che si occupa di parafrasare in maniera immediata frasi oppure interi paragrafi. Questa attività si svolgerà interamente su internet e non lascerà alcuna traccia di plagio