Introduction
With the advent of VS2008, we have the ASP timer control which we can use as a countdown timer. This tip will help in creating a countdown timer using ASP.NET and Ajax.
Background
We get plethora of examples or code samples which show how to use the timer control with Ajax Update panel. These examples will show that the label which is inside the Update panel gets updated with every tick event of the timer. But, if we have to show the duration or the amount of time left, we have to do some work around. The below mentioned description and code snippets will help you or at least give you an idea to approach the situation.
Using the Code
I have used the default website template that ships in with VS2010.
On the Default.aspx page, I have inserted the following lines of code:
// Add the ScriptManager and Timer Control.
<div>
<asp:ScriptManager ID= "SM1" runat="server"></asp:ScriptManager>
<asp:Timer ID="timer1" runat="server"
Interval="1000" OnTick="timer1_tick"></asp:Timer>
</div>
// Add the update panel,
//a label to show the time remaining and the AsyncPostBackTrigger.
<div>
<asp:UpdatePanel id="updPnl"
runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblTimer" runat="server"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="timer1" EventName ="tick" />
</Triggers>
</asp:UpdatePanel>
</div>
On the Default.aspx.cs page, I have the following lines of code:
protected void timer1_tick(object sender, EventArgs e)
{
if (0 > DateTime.Compare(DateTime.Now,
DateTime.Parse(Session["timeout"].ToString())))
{
lblTimer.Text = "Number of Minutes Left: " +
((Int32)DateTime.Parse(Session["timeout"].
ToString()).Subtract(DateTime.Now).TotalMinutes).ToString();
}
}
In the Default.aspx.cs page in the page load event, I had written the following lines of code to create a session variable and ensure that the value of the session variable doesn't get updated due to the async post back caused by the AsyncPostBackTrigger
.
protected void Page_Load(object sender, EventArgs e)
{
if (!SM1.IsInAsyncPostBack)
Session["timeout"] = DateTime.Now.AddMinutes(120).ToString();
}
If we do not include the IsAsyncPostBack
check, our Session
variable will always get updated with the latest or current date time value.
protected void Page_Load(object sender, EventArgs e)
{
Session["timeout"] = DateTime.Now.AddMinutes(120).ToString();
}
In this example, I have hard coded the duration as 120 minutes. This can be fetched from config file. Also, instead of session, one can store the initial time in a hidden label.
Points of Interest
One mistake I made while I was coding is that I did not include the IsAsyncPostBack
check. So, whenever one is dealing with AsyncPostBackTrigger
, please make sure you handle IsAsyncPostBack
of the page properly.
History
- 27th July, 2012: Initial post
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.