技术开发 频道

用ASP.Net AJAX开发Web程序 -- Timer、UpdateProgress篇



    【IT168 专稿】
 
Timer控制顾名思意,它的作用是在固定的时间内刷新UpdatePanel,使其异步更新。它的使用和Windows Form中的Timer作用类似。而UpdateProgress的作用是,当异步更新时服务器处理时间较长时,UpdateProgress控件可以生成提示信息,提示使用者程序正在运行。无疑有了这两个控件,我们写的程序将更加友好。下面我们各用两个示例来说明这两个控件的使用。

一、   使用Timer控件
1.Timer的重要属性/方法
 
属性/方法
说明
Interval
该属性设置多少时间内自动刷新,单位为毫秒。
Tick
当自动刷新时间到了以后,触发该事件。
 
2.      使用Timer控件
 
下面是一段使用Timer控件的简单示例。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Timer.aspx.cs" Inherits="Timer" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
    <script runat="server">
        void Timer1_Tick(object sender, EventArgs e)
        {
            string temp;
            temp = Label2.Text;
            if (temp == "2")
                temp = "3";
            else if (temp == "3")
                temp = "2";
            else
                temp = "2";
            Label2.Text = temp;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        &nbsp;</div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick">
                </asp:Timer>
                <asp:Label ID="Label1" runat="server" Text="Label"><%=DateTime.Now.ToString() %></asp:Label>
                <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>
        &nbsp;&nbsp;
    </form>
</body>
</html>

在上面的代码里面,我们实现了一个异步更新的服务器端时间的效果,Interval设置为1000,表示每一秒种更新一次。并且触发了Tick事件,该事件更改了Label2的Text的属性。通过这个示例,很容易就了解Timer的使用方法了。
 
2.       Timer控件使用总结
 
Timer在程序需要处理定时局部更新的时候,就可以派上用场了。注意Timer会触发所有UpdatePanel的UpdateMode设置为Always的更新。
0
相关文章