UpdatePanel控件(四)——Timer控件(2)

本文介绍如何利用ASP.NET中的Timer控件实现UpdatePanel内容的定时刷新,通过实例展示了如何每秒更新时间并随机显示名言,适用于网页上实时信息的更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Timer控件更典型的应用是:定时刷新UpdatePanel控件的内容。

前台:

    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Timer ID="Timer1" runat="server" Interval="1000">
                </asp:Timer>
                <asp:Label ID="Label2" runat="server" Text="The time is:"></asp:Label>
                <%= DateTime.Now.ToString("T") %><br />
            </ContentTemplate>
        </asp:UpdatePanel>
        <br />
        <fieldset>
            <legend>
                <asp:UpdatePanel ID="up1" runat="server">
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
                    </Triggers>
                    <ContentTemplate>
                        <asp:Label ID="lblQuote" runat="server" Text="The time is:"></asp:Label>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </legend>
        </fieldset>
    </div>

 

后台:

    protected void Page_Load(object sender, EventArgs e)
    {
        List<string> quotes = new List<string>();
        quotes.Add("A fool and his money are soon parted");
        quotes.Add("A penny saved is a penny earned");
        quotes.Add("An apple a day keeps the doctor away");

        Random rnd = new Random();
        lblQuote.Text = quotes[rnd.Next(quotes.Count)];
    }

 

注:Timer控件每隔5秒刷新一次某论坛的信息。如果开着浏览器窗口,即使你去做别的事情,浏览器也能显示最新的信息,因为论坛上的其他人回传了这些内容。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值