[英]How do I stop countdown timer using asp.net timer control?
我在项目中插入了倒数计时器。 当我运行它时,计时器启动,但是当我停止调试它时,并且在一段时间后再次运行它时,我注意到的是计时器仍在运行。 例如,我给计时器分配了3分钟的时间,即3分钟后,它应该重定向到结果页面...现在我运行该页面并开始倒数计时器...当我停止调试时,假设是在00 :02:45(剩余时间),在5秒钟后再次运行时,计时器将继续00:02:40(剩余时间)。 我不想这样发生。 如何停止计时器的继续? 看看我的代码。 告诉我我在哪里犯错误,以及解决方案是什么。
在TimerTest.aspx.cs页面上,我具有以下代码行:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class Student_TimerTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["end_t"] == null)
{
DateTime start_time = DateTime.Now;
DateTime end_time = start_time.AddMinutes(3);
Session["end_t"] = end_time;
}
}
protected void timer1_tick(object sender, EventArgs e)
{
DateTime dt = (DateTime)Session["end_t"];
DateTime dt_curr = DateTime.Now;
TimeSpan ts = dt - dt_curr;
lblTimer.Text = ts.Hours.ToString() + ":" + ts.Minutes.ToString() + ":" + ts.Seconds.ToString();
if (ts.Minutes == 0)
{
timer1.Enabled = false;
Response.Redirect("/Student/Result.aspx");
}
}
}
在TimerTest.aspx页上,我插入了以下代码行:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TimerTest.aspx.cs" Inherits="Student_TimerTest" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID= "SM1" runat="server"></asp:ScriptManager> <asp:Timer ID="timer1" runat="server" Interval="1000" OnTick="timer1_tick"></asp:Timer> </div> <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> </form> </body> </html>
说计时器仍在运行会产生误导。 退出调试后,实际上没有任何代码在运行。 但是 ,您将开始时间存储为会话状态,默认情况下,该状态存储在浏览器中。 如果停止调试然后再次启动,则将重新启动Web应用程序的应用程序实例 ,但浏览器会保留会话状态。 因此,您的浏览器仍然具有旧的启动时间。 因此,在页面加载时, if (Session["end_t"] == null)
结果为false 。 有一个价值存在。
这里有很多选项,但是如果不是回发的话,一种方法是始终清除页面加载时的值。 如果是回发邮件,只需检查会话中是否已有值。
样例代码:
protected void Page_Load(object sender, EventArgs e)
{
// If this is the initial page load (not a post back),
// or if there's not already an end time in Session,
// then set the end time
if (!Page.IsPostBack || Session["end_t"] == null)
{
DateTime start_time = DateTime.Now;
DateTime end_time = start_time.AddMinutes(3);
Session["end_t"] = end_time;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.