2013-10-02 26 views
3

我試圖在asp.net創建一個定時器的UpdatePanel定時器和在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> 

現在根據代碼計時器調用每一秒,但它沒有發生,我嘗試與按鈕和點擊事件相同,但仍然文本不更新,但當我點擊按鈕時刷新頁面。我是否做錯了什麼?

回答

3

如果您正在開發計時器的網頁 - 你必須這樣做的客戶端,使用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函數停止定時器。

你可以嘗試一個工作演示here,它只顯示秒,但你應該明白了。