This tutorial will show you how to use AJAX to count and display in real-time the amount of time a user spends on the page. VB.NET
In this tutorial, you will learn how to use AJAX to continually display and count up the time spent on a page, without disturbing other controls on that page. We will also demonstrate how we can have multiple Asynchronous postbacks on one page without interfering with one another.

This tutorial was written with and aimed at users of Visual Studio 2008 and ASP.NET 3.5. If you are using Visual Studio 2005 and ASP.NET 2.0, then you will need to download the AJAX Extensions from Microsoft in order to utilize AJAX functionality.

For us to display the current time spent on the page, we will have to update a control every second. Fortunately, AJAX allows us to do this quite well. We will use a Literal control to display the time on the page, and we will wrap that in its very own UpdatePanel. This way we are only updating the literal control every second, and not the whole page or other controls.
The first thing to do though is to add the ScriptManager that will handle all of our AJAX calls behind the scenes:

Once that is added, we can add our UpdatePanel, which will set the area to be updated. We also add triggers to this, as we will be using an AJAX Timer control to update the UpdatePanel every 1000 milliseconds:

We create an Asynchronous trigger, and place the Timer and Literal controls in the ContentTemplate. Notice that we set the EventName of our trigger to that of the Timer – the Timer has an event call Tick, which we specify to occur every second (1000 milliseconds). Then we set the event handler for the tick, which references Timer1_Tick, which is in the code-behind. In order to keep the current amount of time recorded, we use a HiddenField to store it on the page. We will then use that value to add a second onto it before we display it to the page:

Now in the code-behind, we set the value of the timer to be zero when the page is first loaded. We set this to the hidden field because on every Tick of the Timer, the value of the hiddenfield is retrieved, converted back to a TimeSpan type, added a second to, and then displayed by the literal. This is repeated every second, and because it is within an UpdatePanel, it is updated instantaneously without postback.

Now if you run this page, you will notice that the timer begins counting up as soon as the page is loaded, and continues to count up each second. Now to demonstrate that we can add some functionality to our page without effecting the counter, let’s add a TextBox and a Button. We will need to add another UpdatePanel to separate from the Timer – we do not want the button to PostBack the whole page:

Our ASPX page and code-behind will look something like this:

Download Source Files