2012-11-15 28 views
1

我創建了一個在線考試網站,我想實現ajax計時器。我已經寫了代碼,但問題是我正在初始化一個會話,併爲該計時器添加no秒,假設爲10秒。並在頁面加載時顯示從6秒。所以我覺得當頁面預渲染完成計時器已經開始這就是爲什麼它顯示從6秒而不是10秒ASP.NET Ajax計時器計數顯示錯誤

這是代碼。如果任何機構可以建議如何從10秒顯示將是很大的。

aspx文件代碼

<body> 
<form id="form1" runat="server"> 
<div> 
    <asp:ScriptManager ID="ScriptManager1" runat="server"> 

    </asp:ScriptManager> 

    <asp:UpdatePanel ID="UpdatePanel1" runat="server"> 
    <ContentTemplate> 
     <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick"> 
     </asp:Timer> 
      <asp:Label ID="Label1" runat="server" Text="Remaining Time :"></asp:Label>&nbsp;<asp:Label ID="lblTime" runat="server" Text=""></asp:Label> 
    </ContentTemplate> 
    </asp:UpdatePanel>   
</div> 
</form> 

CS文件代碼

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
     Session["time"] = DateTime.Now.AddSeconds(10); 
    } 
} 

protected void Timer1_Tick(object sender, EventArgs e) 
{ 
    if (lblTime.Text != "TimeOut!") 
    { 
     TimeSpan time1 = new TimeSpan(); 
     time1 = (DateTime)Session["time"] - DateTime.Now; 
     if (time1.Seconds <= 0) 
     { 
      lblTime.Text = "TimeOut!"; 
      ScriptManager.RegisterStartupScript(this, this.GetType(), "StartUpScript1", "alert('hello')", true); 

     } 
     else 
     { 
      lblTime.Text = time1.Hours.ToString("#00") + ":" + time1.Minutes.ToString("#00") + ":" + time1.Seconds.ToString("#00"); 
     } 
    } 
    else 
    { 
     //Timer1.Interval = 0; 
    } 
} 
+0

答案的答案是? – VMAtm

回答

0

然後您存儲值在會議上,他們是不變的。
您的頁面已加載,且時間已設置。加載後,Timer將Ajax調用發送到Timer1_Tick,並獲得過時的時間。

您需要將您的代碼,時間設置在Timer1_Tick方法,像這樣:

protected void Timer1_Tick(object sender, EventArgs e) 
{ 
    if (Session["time"] == null) 
     Session["time"] = DateTime.Now.AddSeconds(10); 

另一種方法是使用javascript or jquery for countdown timers - 這將照常工作,但刪除頁面回發到服務器。