Detecting Refresh or Post back in ASP.NET
There are situations where we would like to detect if the post back is from a form interaction (i.e. submit or button clicks) or is it by hitting the browser F5 refresh button.
Many of them will jump saying how about checking 'Ispostback' value. 'IsPostback' will always have the value which was set previously. So for instance if the page was posted back before refresh, then the value will be true and if the page is not posted back before refresh, then the value will be false.
This article will first explain the fundamentals of how to solve the above problem and later this article will go in depth of how the source code looks like.
Please feel free to download my free 500 question and answer eBook which covers .NET , ASP.NET , SQL Server, WCF , WPF , WWF , Silver light , Azure @ http://tinyurl.com/4nvp9t
The solution which this article proposes first came in an ASP.NET book written by Dino Esposito and it was taken further by Mr. SimoneB to make a small open source code which you can get from http://sourceforge.net/projects/busybox.
A brief explanation is also provided at this link.
The article will go step by step to explain the ideas proposed by Mr. Dino Esposito in a simplified manner.
. Step 3 :- In 'HttpHandler' or 'HttpModule' the new GUID value is checked with the old GUID value. If the values are not equal then it means this was not called from a submit click and it's a refresh event. Accordingly the HttpContext session value is set.
. Step 4 :- In the page load we can then check if this was a refresh or post back using the session variables.
3 important parts of the code
There are 3 important part of the code to be understood :-
. HtppHandler which checks if the old value is equal to the new value.
. ASP.NET page which finally checks if it's a refresh or postback and handles logic accordingly.
The 'onPostBack'function calls 'generateRandomSequence' function to generate GUID and attach the same to a hidden field with name 'hdnGuid'. This hidden field is generated on fly in the 'HttpHandler' module which will be explained shortly. Below is the code snippet for the same.
var g = "";
for(var i = 0; i < 32; i++)
g += Math.floor(Math.random() * 0xF).toString(0xF)