每隔几秒更新MVC 2视图
本文关键字:更新 MVC 视图 几秒 | 更新日期: 2023-09-27 18:11:08
我使用MVC 2,我有一个视图,它只是显示标签上的当前时间。
我想更新这个视图(标签)每5秒,所以时间会更新。我在下面使用(从这里采取),但似乎没有工作。
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();
}
提前感谢您的帮助!
您所做的将不起作用,因为一旦初始响应被发送到客户端,客户端将不再从服务器侦听该请求的数据。您要做的是让客户机每5秒发起一个新请求,然后简单地返回每个请求的数据。一种方法是使用刷新头。
public ActionResult Time()
{
this.HttpContext.Response.AddHeader( "refresh", "5; url=" + Url.Action("time") );
return View();
}
您需要将循环循环放在客户端,以便它每五秒重新加载页面。
一种方法,使用Javascript:
<script>setTimeout("window.location.reload();",5000);</script>
您提供的代码在服务器上运行,当一个页面(在本例中是View)被发送到客户端时,服务器将忘记它!您应该创建一个客户端代码,用于每5秒刷新一次页面。您可以使用header
命令(refresh
)或脚本:
<script>
setTimeout("window.location.reload();", /* time you want to refresh in milliseconds */ 5000);
</script>
但是如果你只是想刷新页面来更新Time
,我不建议你完全刷新页面。相反,您可以创建一个javascript函数,每5秒打一次勾,计算当前时间并更新标签。