---
title: "ASP之利用updatepanel和Timer实现局部定时刷新"
author: "mywebcode"
date: "2012-10-25T22:07:00Z"
tags: []
slug: "asp-updatepanel-timer"
draft: false
lastmod: "2014-04-19T16:48:09Z"
id: 2049593
url: "https://mywebcode.iteye.com/blog/2049593"
---

default.aspx代码:

```
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<p>我们大阿斯顿疯狂了减肥了金萨克的解放军萨拉克等附近拉斯金东方
    看见了撒娇的疯狂敬爱是考虑到放假了卡斯加的罚款了时间啊数据的飞洒
    地方 近代史可减肥了撒娇的法律进撒旦进房间阿斯兰的客服进来看是激昂
    的弗兰克金阿斯顿路口附近阿斯兰的房间阿斯顿路口附近撒旦可放假了sd卡
    附近的律师费加拉斯金副教授了附近拉经受了附近暗示疗法经受了</p>
    <asp:UpdatePanel ID="updPanel" runat="server">
    <ContentTemplate>
        <asp:Timer ID="timerTest" runat="server" Interval="10000" 
            ontick="timerTest_Tick">
        </asp:Timer>
        <asp:Label ID="lbl" runat="server" Text="Label"></asp:Label>
    </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
```

对应的Default.aspx.cs文件代码:

```
using System;

namespace TestWebApp
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                return;//在此处设置断点,注意debug时是执行这个断点还是执行下面那个断点
            }
            else
            {
                return; ////在此处设置断点,注意debug时是执行这个断点还是执行上面那个断点
            }
        }

        protected void timerTest_Tick(object sender, EventArgs e)
        {
            lbl.Text = DateTime.Now.ToString();
        }
    }
}
```

Default.aspx文件中添加了三个部件

1\. &lt;asp:ScriptManager&gt;&lt;/asp:ScriptManager&gt;  
这个是使用UpdatePanel和Timer控件需要的.

2\. &lt;asp:UpdatePanel&gt;&lt;/asp:UpdatePanel&gt;  
这个是使用局部刷新需要的.

3\. &lt;asp:Timer&gt;&lt;/asp:Timer&gt;  
这个是定时刷新需要的.

Default.aspx.cs文件中有两个函数

1\. Page\_Load函数

页面刷新时,会自动调用这个函数.  
当页面首次加载时Page.IsPostBack==false  
当Timer刷新时Page.IsPostBack==true

2\. timerTest\_Tick定时函数

定时器执行时,将lbl显示为当前时间.