German Wear Discount Shop - Click Here Write for Dotnet-friends and earn for your each submission [Dot]Net-Friends
Skip Navigation Links
Home
Latest
Fast Code
Articles
Tutorials
Online Resources
Forums
Login   | Hi, Guest


Detecting Page Refresh in ASP .NET

Written by khattak2 on Dec 28, 2006
How to detect Page refresh either after postback or by refresh of the Browser

Introducation:

you can’t stop the user from refreshing the page, however there is a way to determine if this event has occurred.
This is a common problem in Web Application Developers that how to stop the user from refreshing the page. This is like if the previous request to the server was a PostBack ( e.g User inserted the WebForm’s data into a database) This results in duplicate rows of the database.

Explanation:

In his article “Build Your ASP.NET Pages on a Richer Bedrock” Dino Esposito outlined a mechanism to detect a page refresh. This method is cumbersome and more complicated than necessary, although the fundamental idea is sound and forms the basis of this solution. Dino’s mechanism uses a counter stored on the page and a session variable to store the previous request’s counter on the server, if the two match then we have a page refresh.


A Simpler Method :

Keeping the whole process within a base Page Class ensures that the mechanism is completely encapsulated (and simple to implement) and if we use ViewState we eliminate the need to use an additional hidden field. Also, as we simply want to test if the two storage devices contain the same value, we can use two boolean variables, which further simplifies the process.

The last decision to make is where, in the Page’s lifecycle, should the process take place. As we are using ViewState it would seem logical to perform the operation in the LoadViewState and SaveViewState methods. Using these two methods, and not the OnLoad method, has further benefits in that it eliminates potential problems with sub-classes implementing Page_Load.


How The Process Works :

The LoadViewState method, which is part of the Page’s initialisation phase, is only invoked during PostBack and therefore SaveViewState is the only method, of the two ViewState related methods, to be called when the page is first requested.

protected override object SaveViewState()
{
Session["__ISREFRESH"] = _refreshState;
object[] allStates = new object[2];
allStates[0] = base.SaveViewState();
allStates[1] = !_refreshState;
return allStates;
}

Note: The _refreshState is retrieved from ViewState and compared with the value in the Session["__ISREFRESH"] item. The result is stored in _isRefresh, which is used by the IsRefresh Property.

The listing below shows the entire class definition:  

namespace StevenBey.Web.UI
{
public partial class Page : System.Web.UI.Page
{
private bool _refreshState;
private bool _isRefresh;

public bool IsRefresh
{
get
{
return _isRefresh;
}
}

protected override void LoadViewState(object savedState)
{
object[] allStates = (object[]) savedState;
base.LoadViewState(allStates[0]);
_refrehState = (bool) allStates[1];
_isRefresh = _refreshState == (bool) Session["__ISREFRESH"];
}

protected override object SaveViewState()
{
Session["__ISREFRESH"] = _refreshState;
object[] allStates = new object[2];
allStates[0] = base.SaveViewState();
allStates[1] = !_refreshState;
return allStates;
}
}
}


Testing The Process:

<%@ Page Inherits="StevenBey.Web.UI.Page" %>

     IsRefresh = <%= IsRefresh %>


Clicking the “Test Refresh” button invokes a PostBack, however the value of IsRefresh doesn’t change until you click on the browser’s Refresh button or press F5 on the keyboard (and then click “Retry”). Clicking the “Test Refresh” button once again resets the value of IsRefresh to false.

Visitors/Readers Comments
(for questions please use The Forum)



Volkan

Hi I et this error message. Do you know Why? Thanks.

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0260: Missing partial modifier on declaration of type 'StevenBey.Web.UI.Page'; another partial declaration of this type exists

Source Error:

 
Line 1:  namespace StevenBey.Web.UI
Line 2:  {
Line 3:      public class Page : System.Web.UI.Page
Line 4:      {
Line 5:          private bool _refreshState;

28/12/2006 17:50:22 UTC

Volkan

I fixed the above error.

I was wondering if you could explain more on testing the page part. Are you want us to insert a button.Because all I see in the page is this IsRefresh = False even if I refresh the page or not refresh the page.

Thanks

28/12/2006 18:17:55 UTC

Kamal

This only gives us an Idea how it works. How we are going to need is some thing different. You need not to show any thing on the page.

On the Page_Load event you can Check if the Page is refreshed or not. If refreshed then dont do update.

28/12/2006 18:49:56 UTC

Eshwar
Is it possible to handle Refresh problem without using Session Variables as my application may idle even for more than 2 hours, I have avoided using sessions. Any help?

19/01/2007 02:08:18 UTC

Friend

Ask questions in the forum. This way it will be viewed and answerd faster. This section is only for comments.

22/01/2007 18:27:34 UTC

Ankit Goel
Can you please give more information on testing? Can you please provide page_load call?

02/04/2007 22:32:48 UTC

Nesh
hi...do u hav codes for ASP as i juz wanna refresh onli part of a page n nt fully...or else even if refresh the whole page...my search history should b thr...is it possible?thanks...

10/12/2007 00:07:33 UTC

Soj

hi, i am facing something different issue, can anybody help me. After save the Data into Sql Tables calling redirect to other page. I want to clear all the controls in the page before redirecting the page. "Save" button click event is the only event firing here.

 

03/01/2008 22:24:35 UTC

manisha
Hi,
I have a problem.
This particular code when used on local machine is working fine, but when it is used on server
it gives an error like "

Object reference not set to an instance of an object.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
_isRefresh = _refreshState == (bool) Session["__ISREFRESH"]; "

Is there any solution? Thanks

26/03/2008 21:56:49 UTC

Sofia David
I had a problem with page refresh and has been searching for the same for one week but this article helped me a lot.
Thanks u very much.
May God bles u......

24/05/2008 00:03:28 UTC

sofia
this code is not working with ajax , when using Update panel

26/05/2008 01:20:51 UTC

Ravi Kumar

 

 

 

{

 

private bool _refreshState;private bool _isRefresh;public bool IsRefreshget

{

 

}

}

 

{

 

 

_refreshState = (

_isRefresh = _refreshState == (

}

 

{

Session[

 

allStates[0] =

allStates[1] = !_refreshState;

 

}

 

{

 

{

Response.Write(

}

 

return _isRefresh;protected override void LoadViewState(object savedState)object[] allStates = (object[])savedState;base.LoadViewState(allStates[0]);bool)allStates[1];bool)Session["__ISREFRESH"];protected override object SaveViewState()"__ISREFRESH"] = _refreshState;object[] allStates = new object[2];base.SaveViewState();return allStates;protected void Button1_Click(object sender, EventArgs e)if (!_isRefresh)"DATA SAVED SuccessFully!");else

{

Response.Write(

}

 

 

}

"DATA NOT SAVED SuccessFully!");

15/07/2008 04:12:09 UTC

Mike
I did not get about where to add the LoadViewState function. Can anyone help...

09/09/2008 03:41:53 UTC

jitender
gud

22/09/2008 05:12:20 UTC

Jothi
Is it possible to maintain in Master page of the application instead of inheriting Page base class?

help me.

03/10/2008 08:49:40 UTC

Code Typo
Hi,

"_refreshState" is mistyped as "_refrehState"

protected override void LoadViewState(object savedState)
{
object[] allStates = (object[]) savedState;
base.LoadViewState(allStates[0]);
_refrehState = (bool) allStates[1];
_isRefresh = _refreshState == (bool) Session["__ISREFRESH"];
}

Thanks,
Sundeep Kumar


25/11/2008 00:40:49 UTC

belal
this code is incorrect

18/12/2008 09:44:17 UTC




Add your Comments

Name:  
Message:
Note: For faster response please use Forums >> for your questions instead of the comments area! (Admin)