ASP.NET计时器重置页面刷新 [英] Asp.net Timer resets on page refresh

查看:70
本文介绍了ASP.NET计时器重置页面刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个简单的asp.net计时器,并将此代码作为后端

I'm using a simple asp.net timer with this code as a backend

protected void Timer1_Tick(object sender, EventArgs e)
{
    int seconds = int.Parse(Label1.Text);
    if (seconds > 0)
        Label1.Text = (seconds - 1).ToString();
    else
        Timer1.Enabled = false;
}

计时器在前端的UpdatePanel中与标签和按钮分组在一起.

The timer is grouped along with a Label and a Button inside a UpdatePanel in my front-end.

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Image ID="RedBox" runat="server" ImageUrl="~/images/redbox.png" Visible="false" CssClass="redbox1" ClientIDMode="Static" />
        <asp:Button ID="schlbtn1" runat="server" Text="Go To Lectures" CssClass="btn btn-lg btn-success btn-block" OnClick="schlbtn1_Click" Visible="true" ForeColor="Black" ViewStateMode="Enabled" ClientIDMode="Static" />
        <asp:Label ID="Label1" runat="server" Visible="false" CssClass="timerlbl" Font-Size="XX-Large">60</asp:Label>
        <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick" Enabled="false">
        </asp:Timer>
    </ContentTemplate>
</asp:UpdatePanel>

我正在寻找一种使计时器在每次页面刷新时都不会重置的方法.即使客户端不在同一页面上,我也需要计时器才能倒数直至达到0.我尝试了睡眠方法,但认为这不是解决方案.请提出任何建议.

I'm looking for a way to make the timer NOT to reset on every page refresh. I need the timer to still count down until it reach 0 even if the client is not on the same page. I tried Sleep methods but think this is not the solution. Please make any kind of suggestions.

推荐答案

将超时存储在会话中:

添加到页面加载中:

if (Session["timer"] == null)
{
    InitTimer(120); // or whatever initial value is
}

添加方法:

public void InitTimer(int secs)
{
    Session.Add("timer", secs);
    Timer1.Enabled = true;
}

更改刻度方法:

protected void Timer1_Tick(object sender, EventArgs e)
{
    int seconds = (int)Session("timer");
    if (seconds > 0)
    {
        seconds--;
        Session["timer"] = seconds;
        Label1.Text = seconds.ToString();
    }
    else
        Timer1.Enabled = false;
}

这篇关于ASP.NET计时器重置页面刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆