Asp.net Timer resets on page refresh

守給你的承諾、 提交于 2020-01-02 21:54:11

问题


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

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>

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.


回答1:


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


来源:https://stackoverflow.com/questions/34491996/asp-net-timer-resets-on-page-refresh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!