This tutorial was written with ASP.NET 3.5 using Visual Studio 2008. If you are using 2005 with ASP.NET 2.0, then you will need to download the AJAX Extensions from Microsoft.

In order to display the time spent on the page, we will have to create an UpdatePanel that updates every second. In order for this to not affect the rest of the page, we will put other functionality in another Update Panel. To programmatically update the time, we will use an AJAX Timer control. But first, let us begin by adding a ScriptManager control to our ASPX page:

the next thing to do is add our UpdatePanel that will display the time spent on this page:

Notice that we have included the triggers tag, as well as the content template. The trigger we are going to use will be an AJAX Timer control. Let’s add that in now, as well as set the Trigger attributes:

We add an AsyncPostBackTrigger and set the control ID and Event Name to match our Timer control. We also set the Interval of the Timer’s tick event to 1000 milliseconds. We have added a Literal control to display the time spent on the page, and then a HiddenField to store that value. We add code to the code-behind that will run every second, on the Tick event of the Timer control (we can do this by simply adding the code manually, or double-clicking the timer control in Design view):

First, on page load we are assigning a new value to the hidden field, of type TimeSpan. This TimeSpan is 0 hours, 0 minutes, and 0 seconds. Then on each Tick event, we add one second to that value, then display it in the Literal control. If we now run this page, we will see the page programmatically and seamlessly count up the time spent on the page.
To demonstrate that this will not interfere with other functions on the page, let’s go ahead and add another Update Panel:

Here, we will ask for the name of the visitor and then display it back to them without posting back. We do this with the following code:

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

Download Source Files