定时器滴答未触发

问题描述

我使用的是 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"));
}

解决方法

尝试将计时器置于 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>
,

问题是,我在 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>