Monday, January 25, 2010

Code Behind the Ajax Control

f (! IsPostBack)
{
hid_Ticker.Value = new TimeSpan(0, 0, 0).ToString();
}
Next, we create the Tick handler, which will retrieve the current time from the HiddenField, add one second to it, and display it in the Literal field, then it will save the new value to the HiddenField to be used again in a second:
protected void Timer1_Tick(object sender, EventArgs e)
{
hid_Ticker.Value = TimeSpan.Parse(hid_Ticker.Value).Add(new TimeSpan(0, 0, 1)).ToString();
lit_Timer.Text = “Time spent on this page: ” + hid_Ticker.Value.ToString();
}
Because AJAX is native to ASP.NET 3.5, we do not need to add anything extra or reference any other namespaces. All we simply need to do is include the ScriptManager and UpdatePanel controls, ASP.NET takes care of everything else for you behind the scenes.
If we run this now the timer will begin counting up as soon as the page is loaded. It is already fully-functional. But to test it, let’s add a textbox and a button so that we can postback the page and demonstrate how to keep the timer counting up regardless.

Finally, we add the logic to the code-behind that will handle the button click event:
protected void btn_Submit_Click(object sender, EventArgs e)
{
lit_Name.Text = “Thanks. Your name is: ” + fld_Name.Text;
}
Now when we run this, you will see that we’re able to submit our name without the timer stopping or pausing or restarting.
Our ASPX page looks like this:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (! IsPostBack)
{
hid_Ticker.Value = new TimeSpan(0, 0, 0).ToString();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
hid_Ticker.Value = TimeSpan.Parse(hid_Ticker.Value).Add(new TimeSpan(0, 0, 1)).ToString();
lit_Timer.Text = “Time spent on this page: ” + hid_Ticker.Value.ToString();
}
protected void btn_Submit_Click(object sender, EventArgs e)
{
lit_Name.Text = “Thanks. Your name is: ” + fld_Name.Text;
}
}