2011-10-13 98 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秒打勾一次,计算当前时间并更新标签。

相关问题