2011-10-13 97 views
2

我正在使用MVC 2,我查看哪個只是顯示帶有當前時間的標籤。每隔幾秒更新一次MVC 2查看

我想每5秒鐘更新一次這個視圖(標籤),所以時間會更新。我在下面使用(取自here),但似乎沒有工作。

public ActionResult Time() 
    { 
     var waitHandle = new AutoResetEvent(false); 
     ThreadPool.RegisterWaitForSingleObject(
      waitHandle, 
      // Method to execute 
      (state, timeout) => 
      { 
       // TODO: implement the functionality you want to be executed 
       // on every 5 seconds here 
       // Important Remark: This method runs on a worker thread drawn 
       // from the thread pool which is also used to service requests 
       // so make sure that this method returns as fast as possible or 
       // you will be jeopardizing worker threads which could be catastrophic 
       // in a web application. Make sure you don't sleep here and if you were 
       // to perform some I/O intensive operation make sure you use asynchronous 
       // API and IO completion ports for increased scalability 
       ViewData["Time"] = "Current time is: " + DateTime.Now.ToLongTimeString(); 
      }, 
      // optional state object to pass to the method 
      null, 
      // Execute the method after 5 seconds 
      TimeSpan.FromSeconds(5), 
      // Set this to false to execute it repeatedly every 5 seconds 
      false 
     ); 

     return View(); 
    } 

感謝您的幫助!

+0

你是從客戶那裏打這個電話嗎? – Xhalent

+0

爲什麼不做客戶端? –

回答

5

你在做什麼都不行,因爲一旦初始響應發送到客戶端,客戶端將不再從您的服務器,以監聽數據請求。你想要做的是讓客戶端每5秒發起一個新請求,然後簡單地返回每個請求的數據。一種方法是使用刷新標題。

public ActionResult Time() 
{ 
    this.HttpContext.Response.AddHeader("refresh", "5; url=" + Url.Action("time")); 

    return View(); 
} 
+0

作品非常感謝! – user570715

+0

接受這個答案如果它回答了你的問題 –

+0

@tvanfosson,我想發送郵件時間是下午4點,當數據庫行更新時,是否有一個簡單的方法,而不使用Signal R?,任何幫助將是偉大的。 – stom

2

您需要將您的重複循環放在客戶端,以便每隔5秒重新載入頁面。

的一種方法,使用Javascript:

<script>setTimeout("window.location.reload();",5000);</script> 
0

您提供的代碼在服務器上運行,當一個頁面(在這種情況下,視圖)發送到客戶端時,服務器將會忘記它!您應該創建一個客戶端代碼,每5秒刷新一次頁面。您可以使用header命令(refresh)或腳本:

<script> 
    setTimeout("window.location.reload();", /* time you want to refresh in milliseconds */ 5000); 
</script> 

但是,如果你只是想刷新頁面來更新Time,我從來不建議你徹底刷新頁面。相反,您可以創建一個JavaScript函數,每5秒打勾一次,計算當前時間並更新標籤。

相關問題