【问题标题】:Update MVC 2 view every few seconds每隔几秒更新一次 MVC 2 视图
【发布时间】:2011-12-07 09:01:26
【问题描述】:

我正在使用 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();
    }

提前感谢您的帮助!

【问题讨论】:

  • 你是从客户端调用这个吗?

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


【解决方案1】:

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

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

    return View();
}

【讨论】:

  • @tvanfosson,我想在下午 4 点和数据库行更新时发送邮件,有没有不使用 Signal R 的简单方法?任何帮助都会很棒。
【解决方案2】:

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

一种方法,使用 Javascript:

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

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2010-12-17
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      相关资源
      最近更新 更多