Atlas学习手记(5):使用服务端定时控件TimerControl


本文示例源代码或素材下载

  主要内容

  1.TimerControl介绍

  2.完整示例

  一.TimerControl介绍

  TimerControl是一个用于服务器端定时器的控件,可用来实时显示数据等,在很多地方都有应用,本文将简单介绍一下TimerControl的使用。一个简单的TimerControl如下:

<atlas:TimerControlrunat="server"Interval="3000"ID="tickerTimer"OnTick="tickerTimer_Tick"/>

  它的属性解释如下:

属性 解释
Interval 时间间隔,隔多长时间刷新一次,单位为ms

  Interval="3000"

OnTick 每隔Interval时间后向服务器端触发事件,是一个服务器端的方法

  OnTick="tickerTimer_Tick"

Enabled 设置TimerControl控件是否可用,通过此属性我们可以自行控制开启和停止定时。

  二.完整示例

  下面我们通过一个简单的示例来演示TimerControl的使用。在很多网站上我们都可以看到一些股票代码等信息,这些数据都是实时刷新的,这里我们模仿一个股票代码示例。

  1.添加ScriptManager,这个不用多说,只要是Atlas应用都必须添加的。设置它的EnablePartialRendering属性为true,这里要用UpdatePanel来做局部刷新。

<atlas:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server" />

  2.添加TimerControl控件

<atlas:TimerControl runat="server" Interval="3000" ID="tickerTimer" OnTick="tickerTimer_Tick" />

  代码很简单,指定间隔的时间为3s,触发的事件为tickerTimer_Tick

  3.添加UpdatePanel,用两个Label来分别显示公司的名称和虚拟股票代码:

<atlas:UpdatePanel runat="server" ID="UpdatePanel1">
  <Triggers>
    <atlas:ControlEventTrigger ControlID="tickerTimer" EventName="Tick" />
  </Triggers>
  <ContentTemplate>
   <h2>Atlas TimerControl Example</h2>
   <asp:Label ID="CompanyName" runat="server" Font-Bold="True" Font-Size="Larger">Tokyo Traders:</asp:Label>
   <asp:Label ID="CompanyValue" runat="server" Font-Bold="True" Font-Size="Larger" ForeColor="Red">20</asp:Label>
  </ContentTemplate>
</atlas:UpdatePanel>

  4.编写一个简单的Web Service,用来返回股票代码,这里我们用产生一个随机数来模拟:

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
/**//// <summary>
/// Summary description for TimerWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TimerWebService : System.Web.Services.WebService {
  public TimerWebService () {
    //Uncomment the following line if using designed components
    //InitializeComponent();
  }
  [WebMethod]
  public string GetCode()
  {
    Random r1 = new Random();
    return r1.Next(20,200).ToString();
  }
}

  5.编写TimerControl的触发事件tickerTimer_Tick,代码很简单,只要把返回的数据显示在Label上就可以了。

protected void tickerTimer_Tick(object sender, EventArgs e)
{
  TimerWebService service = new TimerWebService();
  this.CompanyValue.Text = service.GetCode();
}

  至此一个简单的TimerControl示例就完成了,看一下运行效果,起始的时候:

  

  3s之后:

  

本文作者:
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3