每隔几秒更新一次MVC 2视图

use*_*715 3 c# asp.net-mvc asp.net-mvc-2

我正在使用MVC 2,我有一个视图,它只显示当前时间的标签.

我想每5秒更新一次View(标签),以便更新时间.我在下面使用(取自这里),但似乎没有工作.

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();
    }
Run Code Online (Sandbox Code Playgroud)

提前感谢您的帮助!

tva*_*son 7

一旦初始响应发送到客户端,您正在执行的操作将无法工作,客户端将不再从服务器侦听该请求的数据.您要做的是让客户端每5秒发起一个新请求,然后只返回每个请求的数据.一种方法是使用刷新标头.

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

    return View();
}
Run Code Online (Sandbox Code Playgroud)