ponedjeljak, 19. listopada 2009.

Detect Page Refresh In ASP.NET

Source page is :
http://csharpdotnetfreak.blogspot.com/2009/09/detect-page-refresh-in-aspnet.html

If you have created a aspx page using C# and ASP.NET and have put a button on it. And in the Click event of this button if you are inserting some data in database , after click if user refresh the page than click event gets fired again resulting data insertion to database again, to stop events on the page getting fired on browser refresh we need to write bit of code to avoid it

1. Page Load

protected void Page_Load(object sender, EventArgs e)
{
//dio za provjeru jel se radi o refreshu
if (IsPostBack == false)
{
Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
}
}


2. Page_PreRender

protected void Page_PreRender(object sender, EventArgs e)
{
//dio za provjeru jel se radi o refreshu
ViewState["CheckRefresh"] = Session["CheckRefresh"];
}

3. Insert Click

protected void btnInsert_Click(object sender, EventArgs e)
{
//provjera jel se radi o refreshu i ako ne izvrsi ovu radnju
if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
{
//dio za provjeru jel se radi o refreshu
Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());

#region insert
}
GridView_Pronalazac.DataBind();
}