簡體   English   中英

ASP.NET計時器重置頁面刷新

[英]Asp.net Timer resets on page refresh

我正在使用一個簡單的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;
}

計時器與前端的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>

我正在尋找一種使計時器在每次頁面刷新時都不重置的方法。 即使客戶端不在同一頁面上,我也需要計時器倒計時直到達到0。 我嘗試了睡眠方法,但認為這不是解決方案。 請提出任何建議。

將超時存儲在會話中:

添加到頁面加載:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM