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

时间:2011-10-13 23:28:01

标签: c# asp.net-mvc asp.net-mvc-2

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

我想每5秒钟更新一次View(标签),以便更新时间。我在下面使用(取自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();
    }

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:6)

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

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

    return View();
}

答案 1 :(得分:2)

您需要将重复循环放在客户端,以便每五秒重新加载一次页面。

一种方法,使用Javascript:

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

答案 2 :(得分:0)

您提供的代码在服务器上运行,当页面(在这种情况下为View)发送到客户端时,服务器将忘记它!您应该创建一个客户端代码,每5秒刷新一次页面。您可以使用header命令(refresh)或脚本:

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

但是如果您只想刷新页面以更新Time,我绝不会建议您完全刷新页面。相反,您可以创建一个javascript函数,每隔5秒打勾一次,然后计算当前时间并更新标签。