5,693,062 members and growing! (19,053 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Howto     Intermediate

Detecting Page Refresh

By Altaf Al-Amin

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.
C#, VB, HTML, Windows, .NET, Visual Studio, ASP.NET, Dev

Posted: 28 Apr 2005
Updated: 28 Apr 2005
Views: 83,063
Bookmarked: 55 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
25 votes for this Article.
Popularity: 4.29 Rating: 3.07 out of 5
8 votes, 32.0%
1
1 vote, 4.0%
2
2 votes, 8.0%
3
5 votes, 20.0%
4
9 votes, 36.0%
5

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.

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:

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:

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

About the Author

Altaf Al-Amin


Altaf Najvani
Microsoft Certified Application Developer
Microsoft Certified Solution Developer
Microsoft Certified Technology Specialist (SQL Server 2005)
Microsoft Certified Technology Specialist(Web Applications)

He has done his BS in Computer Science and currently pursing Masters In Project Management. He is currently working as e-Banking Consultant for Commercial Bank Of Dubai.You can reach Altaf at altaf.alamin@gmail.com.
Location: United Arab Emirates United Arab Emirates

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 18 of 18 (Total in Forum: 18) (Refresh)FirstPrevNext
GeneralHere's a way that I think is simplememberSoftMasterG10:12 8 Jan '08  
GeneralDoes not workmembernssidhu7:42 20 Nov '07  
Generalnot working on ajax pagememberLalit Mohan Sharma1:28 28 Oct '07  
GeneralPlease HelpmemberDonVBguy8:01 12 Oct '07  
GeneralGOOD JOB DONEmemberbsvenki9:47 29 Aug '07  
GeneralThanksmemberatarikg15:23 13 Jun '07  
GeneralCan I get C# version of this particular CodesmemberPrajeshrestha19:14 19 Dec '06  
GeneralRe: Can I get C# version of this particular CodesmemberAmitkk23:00 26 Dec '06  
Generaltrack refresh in per page basismemberauxcom3:40 27 Dec '05  
GeneralRe: track refresh in per page basismemberAltaf Al-Amin18:14 4 Feb '06  
Generalyou've committed plagiarismmemberha_ha_ha11:33 4 Sep '05  
GeneralRe: you've committed plagiarismmemberjustfly3:58 29 Dec '05  
GeneralRe: you've committed plagiarismmemberAlbert Einstein.10:35 24 Jan '06  
GeneralRe: you've committed plagiarismmemberMicktion12:56 29 Dec '06  
GeneralRe: you've committed plagiarismmemberandrewlam3:47 4 Jun '07  
GeneralInstead use Page-Cacheabilitymemberyoshijg6:05 5 May '05  
GeneralRe: Instead use Page-CacheabilitymemberKidan7:01 5 May '05  
GeneralRe: Instead use Page-Cacheabilitymemberyoshijg7:30 5 May '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 28 Apr 2005
Editor: Rinish Biju
Copyright 2005 by Altaf Al-Amin
Everything else Copyright © CodeProject, 1999-2008
Web19 | Advertise on the Code Project