Build a Real-Time Clock with ASP.NET 4.0 AJAX in C#
In this tutorial we will build a simple clock to display the current server time on an ASP.NET page. To do this, we will use AJAX to update only the portion of our page that displays the time so that we can keep an accurate time without having to reload the entire web page.
Creating the Website
To begin, create a new ASP.NET Empty Website and add an ASP.NET page named ‘Default.aspx’ to it. Then add the following to the Default.aspx page:
- Add a scriptmanager to the page.
- Add a timer to the page and name it ‘tmrUpdate’. Set the interval property to ’1000′ which corresponds to the length in milliseconds between each tick of the timer. Then, double click the timer in design mode to generate the tmrUpdate_Tick event method.
- Add an updatepanel to the page. Add a ‘<Triggers>’ section to the update panel in source mode. Then, add a new asyncpostbacktrigger to the triggers. Set the controlid property to ‘tmrUpdate’ and the eventname property to ‘Tick’. This will tell our update panel to update only when the tick event of our timer executes. Add a ‘<ContentTemplate>’ to the update panel. Add a label to the content template and name it ‘lblTime’.
Once we have our form setup with a label inside of an update panel that will only be updated in the event that our timer ticks, we are ready to display the time.
Displaying the Time
For this example we will display the current time on the server. Typically client time would be preferred, but for simplicity the time shown in this example will be from the server. To do this, open Default.aspx.cs and add the following code to the tmrUpdate_Tick event method:
protected void tmrUpdate_Tick(object sender, EventArgs e)
lblTime.Text = DateTime.Now.ToString("T");
To test this out load up the web site. Notice that our label displays the current time and updates every second. Without AJAX our entire web page would have to reload every time we want to update our time, which in this case is every second. The benefit to using this method of updating is that only our label is being updated as opposed to the entire web page which can take a lot longer to load than one second.