65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET 中的自动回发

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.43/5 (19投票s)

2005年12月2日

CPOL

2分钟阅读

viewsIcon

212644

如何在 ASP.NET 中实现自动回发。

引言

在 2009 年 7 月 6 日更新本文后,我看到有人认为我不知道今天还有其他解决方案。正如 Stephen Inglish 在一条消息中指出的那样,其中一种方法是使用 AJAX 定时器模块,据我所知,可能还有其他解决方案。

回到 2005 年,当我第一次使用 Visual Studio 2003 编写这篇文章时,我无法找到一个在定期时间表上自动回发的解决方案。 搜索了一段时间,没有找到任何东西,所以我编写了这个 JavaScript 并与 CodeProject 社区分享了它。

文章发表于 2005 年后,社区成员 isikiss 和 obed21 发表了一些评论,改进了代码。 我更新这篇文章的原因,即使它已经过时,是因为仍然有人阅读这篇文章,我认为他们应该得到更新的代码。

使用代码

启动一个新的 ASP.NET Web 应用程序。 随意命名,也许是 TimerTest,然后执行以下操作

在设计模式下,单击“源”按钮,并将此 JavaScript 粘贴到 head 标签内。

<script language="JavaScript" type="text/javascript">
<!--
// Script to generate an automatic postBack to the server
var secs
var timerID = null
var timerRunning = false
var delay = 1000
function InitializeTimer()
{
    // Set the length of the timer,
     // in seconds. Your choise
    secs = 5

    StopTheClock()
    StartTheTimer()
}
function StopTheClock()
{
    if(timerRunning)
        clearTimeout(timerID)
    timerRunning = false
}
function StartTheTimer()
{
    if (secs==0)
    {
        StopTheClock()

        //Generate a Postback to the server
        document.forms[0].submit()  
     
    }
    else
    {
        secs = secs - 1
        timerRunning = true
        timerID = self.setTimeout("StartTheTimer()", delay)
    }
}
//-->
</script>

您的 Body 应该看起来像这样。 最重要的是在 <body> 标签内添加 onload="InitializeTimer()"

<body onload="InitializeTimer()">
<form id="form1" runat="server">
 <div>
       The time is:   <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>

在代码隐藏文件中,您可以粘贴以下代码,只是为了看到一些事情发生。

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
          Handles Me.Load

  'This is just to se something happening
  Label1.Text = Now.ToString("hh:mm:ss")

  'Put the code to execute here.
End Sub

保持原样。 它所做的只是回发到服务器,在这个例子中,它每 5 秒刷新一次时间。

就这样了。

历史

  • 2009 年 7 月 6 日:这篇文章是在我使用 Visual Studio 2003 时创建的。 社区成员 isikiss 和 obed21 也发表了一些评论,改进了代码。 我已经实现了他们建议的改进,并使用 Visual Studio 2008 对其进行了测试。
© . All rights reserved.