如何在asp.net中使Ajax计时器正确递减
本文关键字:计时器 Ajax 中使 asp net | 更新日期: 2023-09-27 18:09:27
我正在做一个在线考试项目,在这个项目中我必须显示一个倒计时,直到考试结束。我使用了以下代码:
aspx代码:
<asp:ScriptManager ID= "SM1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel id="updPnl" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblTimer" style=" margin-top:35px; margin-left:825px;" runat="server" Font-Bold="True" Font-Names="Arial" Font-Size="X-Large" ForeColor="#6600CC"></asp:Label>
<div style="margin-right:25px;">
<asp:AlwaysVisibleControlExtender ID="AlwaysVisibleControlExtender1" runat="server" TargetControlID="lblTimer">
</asp:AlwaysVisibleControlExtender>
<asp:Timer ID="timer1" runat="server"
Interval="1000" OnTick="timer1_tick"></asp:Timer>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="timer1" EventName ="tick" />
</Triggers>
</asp:UpdatePanel>
后面的代码是:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bind();
bind1();
Result();
Session["Result"] = lblshow.Text;
if (!SM1.IsInAsyncPostBack)
{
SqlConnection sqlc1 = new SqlConnection(strcon);
sqlc1.Open();
String str = "select top 1 * from TestCreated order by Id desc";
SqlCommand cmd1 = new SqlCommand(str, sqlc1);
//sqlc.Open();
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.Read())
{
Session["timeout1"] = dr["TestDuration"].ToString();
}
Session["timeout"] DateTime.Now.AddMinutes(Convert.ToInt32(Session["timeout1"].ToString())).ToString();
}
}
}
protected void timer1_tick(object sender, EventArgs e)
{
if (Session["timeout"] == null)
Session["time"] = DateTime.Now.AddSeconds(10);
if (0 > DateTime.Compare(DateTime.Now, DateTime.Parse(Session["timeout"].ToString())))
{
lblTimer.Text = string.Format("Time Left: 00:{0}:{1}", ((Int32)DateTime.Parse(Session["timeout"].ToString()).Subtract(DateTime.Now).TotalMinutes).ToString(), ((Int32)DateTime.Parse(Session["timeout"].ToString()).Subtract(DateTime.Now).Seconds).ToString());
}
这段代码在本地服务器上工作得很好,但是当我在我的web服务器上部署它时,计时器没有正确计数,它减少了4秒和5秒,就像这样。甚至我试着改变我的计时器间隔,但它不起作用。我怎样才能使这个计时器正确倒计时?
// 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>
这将为您工作@Skoar..
关于代码项目的更多细节
aspx code is:
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();
}
}