【问题标题】:Timer Tick not firing定时器滴答未触发
【发布时间】:2021-06-16 22:09:40
【问题描述】:

我正在使用 ASP.NET Web 窗体,但有一个小问题。

我希望表单每 1 秒更新一次,但我不希望它重新加载整个页面。

在谷歌上搜索了大部分时间后,我得到了这段代码,但是它仍然没有触发滴答动作。

<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="True"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="masterTimer" EventName="Tick" />
    </Triggers>
    <ContentTemplate>
        <asp:Timer ID="masterTimer" runat="server" ontick="masterTimer_Tick" Interval="1000"></asp:Timer>
    </ContentTemplate>
</asp:UpdatePanel> 

所有这个勾号要做的就是将当前时间添加到列表框中。这是另一个问题出现的地方。列表框是否也需要以某种方式包装在上面的代码中,这是导致问题的原因吗?

protected void masterTimer_Tick(object sender, EventArgs e)
{
    priList.Items.Add(DateTime.Now.ToString("HH:mm:ss"));
}

【问题讨论】:

  • 如果您对 asp.net 非常陌生,请不要使用这个非常旧且过时的 asp.net 版本。使用 .Net 5 升级到 asp.net MVC 或 Blazor。
  • 哦,好吧,我刚刚从 Visual Studios 创建了一个 WebForm。我现在要查一下。谢谢!
  • 是的,Web 表单在 2003 年很酷。现在它们已经很老了
  • 你有没有打电话给masterTimer.Start();或设置masterTimer.Enabled = true;

标签: c# asp.net webforms


【解决方案1】:

尝试将计时器放在 UpdatePanel 之外并设置 UpdateMode 条件。

<asp:Timer ID="masterTimer" Interval="1000" runat="server" OnTick="masterTimer_Tick"></asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        ...
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="masterTimer" EventName="tick" />
        <asp:PostBackTrigger ControlID="Button1" />
    </Triggers>
</asp:UpdatePanel>

【讨论】:

    【解决方案2】:

    问题是,我在 ContentTemplate 中没有项目(即列表框)

    <asp:Timer runat="server" id="priTimer" interval="5000" ontick="priTimer_Tick" />
        <asp:UpdatePanel runat="server" id="TimedPanel" updatemode="Conditional">
            <Triggers>
                <asp:AsyncPostBackTrigger controlid="priTimer" eventname="Tick" />
            </Triggers>
            <ContentTemplate>
                 <asp:ListBox ID="priList" runat="server" style="font-size: 1vw; OVERFLOW:auto; width:100%"></asp:ListBox>
            </ContentTemplate>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多