在ASP.NET中的Timer和UpdatePanel

3

我正在尝试在ASP.NET中创建一个计时器。

Public Class _Default
Inherits System.Web.UI.Page
Dim min As Integer
Dim sec As Integer
Dim hr As Integer
Dim totalTime As Integer
Dim timerStr As String

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    totalTime = 5340
    hr = Math.Floor(totalTime / 3600)
    min = 30
    sec = totalTime Mod 60
    timerStr = String.Format("{0:00}:{1:00}:{2:00}", hr, min, sec)
    label1.Text = timerStr
End Sub


Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs)
    Display()
    label1.Text = timerStr
End Sub
Protected Sub Display()
    totalTime -= 1
    hr = Math.Floor(totalTime / 3600)
    sec = totalTime Mod 60
    If sec = 0 Then
        min = (totalTime / 60) Mod 60
    End If
    timerStr = String.Format("{0:00}:{1:00}:{2:00}", hr, min, sec)
End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
    Display()
    label1.Text = timerStr
End Sub
End Class

//更新面板代码

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick">
</asp:Timer>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" 
    RenderMode="Inline">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
    </Triggers>
     <ContentTemplate>
        <asp:Label ID="label1" runat="server"></asp:Label> 
    </ContentTemplate>
</asp:UpdatePanel>

现在根据代码计时器每秒调用一次,但这并没有发生。我尝试了相同的按钮和点击事件,但仍然无法更新文本,但当我点击按钮时页面会刷新。我做错了什么吗?

1个回答

3
如果您要为Web页面开发计时器,必须在客户端使用JavaScript进行开发,因为一旦服务器端代码运行并将页面呈现给浏览器,服务器端代码就完成了,不再参与页面生命周期。

这是客户端定时器的简化示例。它有一个标签(在浏览器中成为SPAN)和2个按钮-启动和停止计时器:

<span id="Label1" >Seconds: 0</span>

<button id="Button1" onclick="startResetTimer()">Start/Reset</button>
<button id="Button2" onclick="stopTimer()" disabled="disabled">Stop</button>

以下是负责计时器的 JavaScript 代码:

var time; 
var interval;

function startResetTimer() {

    document.getElementById('Button1').disabled = "disabled";
    document.getElementById('Button2').disabled = "";

    time = 0;
    interval = setInterval(function() {
        time++;
        document.getElementById('Label1').innerHTML = "Seconds: " + time
    }, 1000)
}

function stopTimer() {

    document.getElementById('Button1').disabled = "";
    document.getElementById('Button2').disabled = "disabled";

    clearInterval(interval)
}

当您点击“开始/重置”按钮时 - 计时器通过setInterval函数启动。当您点击“停止”时,计时器通过clearInterval函数停止。
您可以在此处尝试工作演示,它仅显示秒数,但您应该能够理解。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接