Detect Page Refresh In ASP.NET

This post explains how to Detect Page Refresh In ASP.NET 2.0,3.5,4.0 Using C# And VB.NET. If you have created a aspx page and have put a button on it, And in 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

In this example i've put a Label and a Button on the page, on click the label Text becomes Hello and when i refresh the page label's text again becomes Hello.

HTML SOURCE OF PAGE
<%@ 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>

In 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
C# Code Bihind
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"];
}
}


Download the Sample Code



24 comments:

  1. I think it's stopped not only insert second record on refresh but at all.

    ReplyDelete
  2. btw: download code is not working...

    ReplyDelete
  3. @Above : please tell me what actually you want to say , i m not getting you

    ReplyDelete
  4. This comment has been removed by a blog administrator.

    ReplyDelete
  5. Do you mean to say: other than manually user clicks button or dropdown selection change(autopostback=true)....

    There may be chances of refresh the page like pressing F5, where it will execute the button click event/something else.... which is not correct.....

    By using above code given by you can we detect!!!

    ReplyDelete
  6. dont understand the code

    ReplyDelete
  7. Thanks for the post! Its a great idea, works great

    ReplyDelete
  8. wohoo, it works :)

    ReplyDelete
  9. How Can i Get Page_Prerender event

    ReplyDelete
  10. @Priya:

    Hi priya just write below mentioned code anywhere in your code behind page

    protected void Page_PreRender(object sender, EventArgs e)
    {
    }

    ReplyDelete
  11. after session timeout this code is not usefull

    ReplyDelete
  12. Hi,

    I have some clarification.Can you please check it metioned below:
    When I click the button then the Session and ViewState are compared and found equal and then it enters the if condition and then the Session value is updated once again and the same session value is updated to ViewState value in the PreRender event.

    Again when I gone for the refresh event by clicking the F5 button then the ViewState variable is not updated with the latest updated value but with the old ViewState value.Hence the if condition was not matching and the else condtion was executed.

    Can you explain why it behaved in such manner?

    Thanks,
    Santosh

    ReplyDelete
  13. Good post! I tried this in C# and it works well.

    Sadly, my ASP project is in VB therefore I wonder if you could provide the relevant code to detect the page refresh?

    Simply copy and paste the code into a C# to VB converter simply doesn't do the job (I tried!). The events that get fired appear differently compared to C#.

    Thanks :)

    ReplyDelete
  14. Suppose If I click the refresh button which is next to URL line then how can i stop the page from refresh? Is there any solution for that ?

    ReplyDelete
  15. Excellent! Thank you!

    ReplyDelete
  16. amiT jaiN

    Its really done what i needed. Thanks.

    ReplyDelete
  17. i had a form of asp.net,on clicking on view 2 my page should not get refresh ,so for that what shd i use the code plz help me

    ReplyDelete
  18. Awesome Amit! Great coder, thanks

    event planning software

    ReplyDelete
  19. Its working please re-check..
    thanks for shareing

    ReplyDelete
  20. I have a datepicker when I refresh the page the date disappears how to fix

    ReplyDelete
  21. Great Idea...it works

    ReplyDelete
  22. Doesn't work in VB. It only works during runtime. When the code is placed on my IIS server, for some reason, at the Button_Click event it always display a newer Session timestamp compare to the one in Form_Load. Therefore, the Session timestamp is always newer than the Viewstate. What is wrong with my code?

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
    Session("CheckRefresh") = Server.UrlDecode(Now.ToString)
    EndIf
    End Sub

    Protected Sub button_Click(sender As Object, e As System.Web.UI.ImageClickEventArgs)
    If (Session("CheckRefresh").ToString = ViewState("CheckRefresh").ToString) Then
    Session("CheckRefresh") = Server.UrlDecode(Now.ToString)
    End If
    End Sub

    Protected Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
    ViewState("CheckRefresh") = Session("CheckRefresh")
    End Sub

    ReplyDelete
  23. From my previous post dated: July 11, 2012 5:02 AM

    I found out what is the problem. My button's "OnClientClick" actually calls a javascript function which will modify a hiddenfield's value. Therefore, somehow when this is run on the server (not runtime), it won't work. I removed the javascript function and it works now.

    ReplyDelete
  24. THIS CODE IS WOORKING BUT MY AJAX ACORDIN cONTOL IS aFFECTION IN THIS SITUATION WHAT WILL I dO

    ReplyDelete