本文主要通过一个简单示例,让Web页面在一定的时间间隔内局部刷新,来学习一下ASP.NET AJAX中的服务端Timer控件的简单使用。<?XML:NAMESPACE PREFIX = O />

 

主要内容

    Timer控件的简单使用

 

1.添加新页面并切换到设计视图。

2.如果页面没有包含ScriptManager控件,在工具箱的AJAX Extensions标签下双击ScriptManager控件添加到页面中。

<?XML:NAMESPACE PREFIX = V />

3.单击ScriptManager控件并双击UpdatePanel控件添加到页面中。

4.在UpdatePanel控件内单击并双击Timer控件添加到UpdatePanel中。Timer控件可以作为UpdatePanel的触发器不管是否在UpdatePanel中。

5.设置Interval属性为10000Interval属性的单位是毫秒,所以我们设置为10000,相当于10秒钟刷新一次。

6.在UpdatePanel控件中添加一个Label控件。

7.设置Label控件的Text属性为“Panel not refreshed yet  ”。确保Label控件添加在了UpdatePanel控件里面。

8.在UpdatePanel之外再添加一个Label控件。确保第二个Label控件在UpdatePanel的外面。

9.双击Timer控件添加Tick事件处理,在事件处理中设置Label1Text属性为当前时间。
None.gifprotected void Timer1_Tick(object sender, EventArgs e)
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    Label1.Text 
= "Panel refreshed at: " +
InBlock.gif
InBlock.gif      DateTime.Now.ToLongTimeString();
ExpandedBlockEnd.gif}
10.在Page_Load事件中添加代码设置Label2Text属性为页面创建时间,如下代码所示:
None.gifprotected void Page_Load(object sender, EventArgs e)
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    Label2.Text 
= "Page created at: " +
InBlock.gif
InBlock.gif      DateTime.Now.ToLongTimeString();
ExpandedBlockEnd.gif}
11.切换到代码视图,确保代码如下所示:
None.gifprotected void Page_Load(object sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    Label2.Text 
= "Page created at: " +
InBlock.gif
InBlock.gif      DateTime.Now.ToLongTimeString();
ExpandedBlockEnd.gif}

None.gif
None.gif
protected void Timer1_Tick(object sender, EventArgs e)
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    Label1.Text 
= "Panel refreshed at: " +
InBlock.gif
InBlock.gif      DateTime.Now.ToLongTimeString();
ExpandedBlockEnd.gif}
12.保存并按Ctrl + F5运行

13.等待10秒钟后可以看到Panel刷新,里面的Label文字改变为刷新的时间而外面的Label没有改变。

 

[翻译自官方文档]