简体   繁体   English

ASP.NET计时器重置页面刷新

[英]Asp.net Timer resets on page refresh

I'm using a simple asp.net timer with this code as a backend 我正在使用一个简单的asp.net计时器将此代码作为后端

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;
}

The timer is grouped along with a Label and a Button inside a UpdatePanel in my front-end. 计时器与前端的UpdatePanel中的Label和Button分组在一起。

<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>

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. 即使客户端不在同一页面上,我也需要计时器倒计时直到达到0。 I tried Sleep methods but think this is not the solution. 我尝试了睡眠方法,但认为这不是解决方案。 Please make any kind of suggestions. 请提出任何建议。

Store the timeout in the session: 将超时存储在会话中:

Add to page load: 添加到页面加载:

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

Add method: 添加方法:

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

Change tick method: 更改勾号方法:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM