【问题标题】:ASP.NET Ajax Timer count shows wrongASP.NET Ajax Timer 计数显示错误
【发布时间】:2012-11-03 18:31:54
【问题描述】:

我创建了一个在线考试网站,我想在其中实施 ajax 计时器。我已经编写了代码,但问题是我正在初始化一个会话,并为计时器添加秒数,假设为 10 秒。当页面加载它显示从 6 秒。所以我觉得当页面预渲染完成时,计时器已经开始,这就是为什么它从 6 秒而不是 10 秒显示的原因

这是代码。如果任何机构可以建议如何从 10 秒开始显示将是非常好的。

aspx文件代码

<body>
<form id="form1" runat="server">
<div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">

    </asp:ScriptManager>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick">
        </asp:Timer>
           <asp:Label ID="Label1" runat="server" Text="Remaining Time :"></asp:Label>&nbsp;<asp:Label ID="lblTime" runat="server" Text=""></asp:Label>
    </ContentTemplate>
    </asp:UpdatePanel>        
</div>
</form>

cs文件代码

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Session["time"] = DateTime.Now.AddSeconds(10);
    }
}

protected void Timer1_Tick(object sender, EventArgs e)
{
    if (lblTime.Text != "TimeOut!")
    {
        TimeSpan time1 = new TimeSpan();
        time1 = (DateTime)Session["time"] - DateTime.Now;
        if (time1.Seconds <= 0)
        {
            lblTime.Text = "TimeOut!";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "StartUpScript1", "alert('hello')", true);

        }
        else
        {
            lblTime.Text = time1.Hours.ToString("#00") + ":" + time1.Minutes.ToString("#00") + ":" + time1.Seconds.ToString("#00");
        }
    }
    else
    {
        //Timer1.Interval = 0;
    }
}

【问题讨论】:

  • 有答案吗?

标签: asp.net ajax timer asp.net-ajax countdowntimer


【解决方案1】:

然后你将值存储在 Session 中,它们是不变的。
您的页面已加载,并且时间已设置。加载后,Timer 将 Ajax 调用发送到Timer1_Tick,并获取过期时间。

您需要在Timer1_Tick 方法中移动您的时间设置代码,如下所示:

protected void Timer1_Tick(object sender, EventArgs e)
{
    if (Session["time"] == null)
        Session["time"] = DateTime.Now.AddSeconds(10);

其他方法是使用javascript or jquery for countdown timers - 这将照常工作,但会删除页面回发到服务器。

【讨论】:

    猜你喜欢
    • 2020-03-30
    • 2018-03-02
    • 2011-12-08
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多