Click here to Skip to main content
15,879,326 members
Articles / Web Development / HTML
Article

Detecting Page Refresh

Rate me:
Please Sign up or sign in to vote.
3.15/5 (32 votes)
28 Apr 20053 min read 251.5K   1.5K   77   28
A common problem that Web application developers encounter is how to stop the user from refreshing the page. So What to do? Although we can’t stop the user from refreshing the page but we can determine if this event has already occurred and then take appropriate action.

Introduction

A common problem that Web Application developers encounter is how to stop the user from refreshing the page. The problem arises, if the previous request to the server was a PostBack, which, for example, inserts the WebForm’s data into a database. This will result in the addition of duplicate rows in the database. But we have a constraint that we can’t stop the user by refreshing the page. So, what to do? Although we can’t stop the user from refreshing the page, but we can determine if this event has already occurred and then take appropriate action.

This article is the result of inspiration from the article “Build Your ASP.NET Pages on a Richer Bedrock” by Dino Esposito in which the author has outlined a mechanism to detect page refreshes. But the problem with this method is that it is cumbersome and complicated, 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.

Strategy

My strategy will make use of the ViewState feature. As we are using ViewState, it would seem logical to perform the operation in the LoadViewState and SaveViewState methods. Using these two methods, instead of the OnLoad method, has more benefits in that it eliminates the potential problems of sub-classes implementing Page_Load. Let’s have a look at these methods first:

LoadViewState

The LoadViewState method loads the previously saved ViewState. The savedState object contains the saved view state values for the item.

SaveViewState

Saves any server control view-state changes that has occurred since the time the page was posted back to the server.

Returns the server control's current view state. If there is no view state associated with the control, this method returns a null reference (Nothing in Visual Basic).

How the process works

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

Note: _refreshState (which on initial page request is defaulted to False and on subsequent PostBack requests, is the value of ViewState) is assigned to the Session["__ISREFRESH"] item and the negated _refreshState is saved to the new ViewState.

VB
Protected Overrides Function SaveViewState() As Object
 Session("__ISREFRESH") = _refreshState
 Dim AllStates() As Object = New Object(2) {}
 AllStates(0) = MyBase.SaveViewState
 AllStates(1) = Not (_refreshState)
Return AllStates
End Function

Once a PostBack event takes place the LoadViewState method is called:

VB
Protected Overrides Sub LoadViewState(ByVal savedState As Object)
 Dim AllStates As Object() = savedState
 MyBase.LoadViewState(AllStates(0))
 _refreshState = Boolean.Parse(AllStates(1))
 _isRefresh = _refreshState = Session("__ISREFRESH")
End Sub

Note: The _refreshState is retrieved from the 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:

VB
Public Class test1
   Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "
   'This call is required by the Web Form Designer.
   <System.Diagnostics.DebuggerStepThrough()> 
   Private Sub InitializeComponent()
   End Sub

   Protected WithEvents Button1 As System.Web.UI.WebControls.Button
   Protected WithEvents label1 As System.Web.UI.WebControls.Label

   'NOTE: The following placeholder declaration is 
   'required by the Web Form Designer.

   'Do not delete or move it.

   Private designerPlaceholderDeclaration As System.Object

   Private Sub Page_Init(ByVal sender As System.Object, 
             ByVal e As System.EventArgs) Handles MyBase.Init
   'CODEGEN: This method call is required by the Web Form Designer
   'Do not modify it using the code editor.

   InitializeComponent()

   End Sub

#End Region

   Private _refreshState As Boolean
   Private _isRefresh As Boolean

   Private Sub Page_Load(ByVal sender As System.Object, 
            ByVal e As System.EventArgs) Handles MyBase.Load
     'Put user code to initialize the page here
     Me.label1.Text = _isRefresh.ToString
   End Sub

   Protected Overrides Sub LoadViewState(ByVal savedState As Object)
     Dim AllStates As Object() = savedState
     MyBase.LoadViewState(AllStates(0))
     _refreshState = Boolean.Parse(AllStates(1))
     _isRefresh = _refreshState = Session("__ISREFRESH")
   End Sub

   Protected Overrides Function SaveViewState() As Object
     Session("__ISREFRESH") = _refreshState
     Dim AllStates() As Object = New Object(2) {}
     AllStates(0) = MyBase.SaveViewState
     AllStates(1) = Not (_refreshState)
     Return AllStates
   End Function
End Class

When you click the control which fires PostBack event, LoadViewState event is executed. This function loads the previously saved ViewState and here we retrieve the refresh state to find out whether the page is requested to be refreshed. The crucial part is checking whether the value of _refreshstate and the one stored in session is the same, if yes it means the user has hit the Refresh Button.

The SaveViewState function saves the current _refreshState value in session so that we can check this later on, to find out whether the Refresh button is hit.

Conclusion

In this article I have tried to demonstrate a simplified method of detecting a page refresh event.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United Arab Emirates United Arab Emirates
Altaf Al-Amin Najvani
Project Manager
Commercial Bank Of Dubai


Qualifications:
BS - Computer Science
Masters In Project Management
Masters In Business Administration

Certifications:
CISA - Certified Information Systems Auditor
ITIL (Foundation)
Microsoft Certified Technology Specialist (SQL Server 2005)
Microsoft Certified Technology Specialist (Web Applications)
Microsoft Certified Application Developer (.NET)
Microsoft Certified Solution Developer (.NET)

Comments and Discussions

 
SuggestionFirst Refresh and Avoid Server Load Balance Pin
fkfouri15-Mar-13 10:50
fkfouri15-Mar-13 10:50 
GeneralMy vote of 3 Pin
rajnish2patel7-Dec-12 6:19
rajnish2patel7-Dec-12 6:19 
QuestionWant a simple working solution? Pin
bgmate27-Oct-11 16:27
bgmate27-Oct-11 16:27 
GeneralMy vote of 1 Pin
omayhemo13-Oct-10 10:47
omayhemo13-Oct-10 10:47 
Generalwhy the value of _isrefresh will true in case of refresh click Pin
kng_kong1128-Jul-10 21:49
kng_kong1128-Jul-10 21:49 
Generalvery first refresh Pin
kianlina@yahoo.co.in15-Jul-10 23:53
kianlina@yahoo.co.in15-Jul-10 23:53 
GeneralHere's a way that I think is simple Pin
SoftMasterG8-Jan-08 9:12
SoftMasterG8-Jan-08 9:12 
GeneralDoes not work Pin
nssidhu20-Nov-07 6:42
nssidhu20-Nov-07 6:42 
Generalnot working on ajax page Pin
L Mohan28-Oct-07 0:28
L Mohan28-Oct-07 0:28 
GeneralPlease Help Pin
DonVBguy12-Oct-07 7:01
DonVBguy12-Oct-07 7:01 
GeneralGOOD JOB DONE Pin
bsvenki29-Aug-07 8:47
bsvenki29-Aug-07 8:47 
GeneralThanks Pin
Tarik Guney13-Jun-07 14:23
Tarik Guney13-Jun-07 14:23 
QuestionCan I get C# version of this particular Codes Pin
Prajeshrestha19-Dec-06 18:14
Prajeshrestha19-Dec-06 18:14 
AnswerRe: Can I get C# version of this particular Codes Pin
Amit Kushwaha26-Dec-06 22:00
Amit Kushwaha26-Dec-06 22:00 
GeneralRe: Can I get C# version of this particular Codes Pin
MadhuSadlapur22-Jan-11 23:45
MadhuSadlapur22-Jan-11 23:45 
AnswerRe: Can I get C# version of this particular Codes Pin
rajnish2patel7-Dec-12 6:20
rajnish2patel7-Dec-12 6:20 
Generaltrack refresh in per page basis Pin
auxcom27-Dec-05 2:40
auxcom27-Dec-05 2:40 
GeneralRe: track refresh in per page basis Pin
Altaf Al-Amin4-Feb-06 17:14
Altaf Al-Amin4-Feb-06 17:14 
Generalyou've committed plagiarism Pin
ha_ha_ha4-Sep-05 10:33
ha_ha_ha4-Sep-05 10:33 
GeneralRe: you've committed plagiarism Pin
justfly29-Dec-05 2:58
justfly29-Dec-05 2:58 
GeneralRe: you've committed plagiarism Pin
Tad McClellan24-Jan-06 9:35
professionalTad McClellan24-Jan-06 9:35 
GeneralRe: you've committed plagiarism Pin
Micktion29-Dec-06 11:56
Micktion29-Dec-06 11:56 
GeneralRe: you've committed plagiarism Pin
EspressoShot4-Jun-07 2:47
EspressoShot4-Jun-07 2:47 
If you take web.archive.org as gospel then the author of this article is the plagiarist.

http://web.archive.org/web/*/http://www.codeproject.com/aspnet/Detecting_Refresh.asp
First updated Dec 04, 2005

http://web.archive.org/web/*/http://stevenbey.co.uk/detectingPageRefresh.aspx
First updated Nov 04, 2005
GeneralRe: you've committed plagiarism Pin
stevenbey18-Feb-12 6:09
stevenbey18-Feb-12 6:09 
GeneralInstead use Page-Cacheability Pin
yoshijg5-May-05 5:05
yoshijg5-May-05 5:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.