Avoid duplicate insertion of record on page refresh by F5

With the help of TimeStamp, we can easily avoid duplicate insertion of record when user refreshes page by pressing F5.
Let's see how easy it is to check whether page is refreshed by pressing F5:

1. First, add a class 'BasePage' to your project and inherit it from System.Web.UI.Page
Here is the detailed code for BasePage class:



public class BasePage : System.Web.UI.Page
//Inherit class from System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["RefreshTimeStamp"] = HttpContext.Current.Server.UrlDecode(System.DateTime.Now.ToString());
}
}

protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["RefreshTimeStamp"] = Session["RefreshTimeStamp"];
}

public bool IsRefreshed
{
get
{
if (Convert.ToString(Session["RefreshTimeStamp"]) == Convert.ToString(ViewState["RefreshTimeStamp"]))
{
Session["RefreshTimeStamp"] = HttpContext.Current.Server.UrlDecode(System.DateTime.Now.ToString());
return false;
}
else
{
return true;
}
}
}
}



2. Now on Default.aspx we will check for page refresh.
Inherit Default.aspx from BasePage instead of System.Web.UI.Page.
and using IsRefreshed property in BasePage, we can easily detect page refresh.


public partial class _Default : BasePage
//Inherit page from BasePage
{
protected void Button1_Click(object sender, EventArgs e)
{
if (!IsRefreshed)
{
// Your Code
}
}
}

Comments

Popular posts from this blog

GROUP BY, CUBE, ROLLUP and SQL SERVER 2005

How to get content of Ckeditor & Fckeditor using Javascript

How to Fix Error- Sys.WebForms.PageRequestManagerTimeoutException - The server request timed out