Monday, August 23, 2010

Detect Page Refresh In ASP.NET

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.

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"
Text="Label"></asp:Label><br />
<br />
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click"
Text="Button" /></div>
</form>
</body>
</html>

Now in the Page_Load event i m creating a Session Variable and assigning System date and time to it , and in Page_Prerender event i am creating a Viewstate variable and assigning Session variable's value to it
Than in button's click event i am checking the values of Session variable and Viewstate variable if they both are equal than page is not refreshed otherwise it has been refreshed.

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString()); }  } protected void Button1_Click(object sender, EventArgs e) { if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString()) { Label1.Text = "Hello"; Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString()); } else { Label1.Text = "Page Refreshed"; } }  protected void Page_PreRender(object sender, EventArgs e) { ViewState["CheckRefresh"] = Session["CheckRefresh"]; } } 

No comments: