65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 ASP.NET Ajax 和 C# 创建服务器端时钟控件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.29/5 (11投票s)

2008年6月3日

GPL3

3分钟阅读

viewsIcon

95196

downloadIcon

2292

演示 Timer 控件和 UpdatePanel 以触发定时服务器事件。

引言

在本文中,我们将学习如何在自定义控件中使用 ASP.NET 的 Timer Updatepanel 控件来创建其他包装控件。

先决条件

要使用它,您至少需要 .NET Framework 2.0 和 ASP.NET AJAX 扩展控件。

背景

使用 Timer,我们可以按时重复任何一组命令。使用 Updatepanel,我们可以在异步模式下处理我们的请求。为了演示这一点,我将向您展示一个简单的服务器端时钟控件。我将在 TimerTick 事件上放置一组指令,然后将其包装在 Updatepanel 中。并且每秒钟,时钟将自行刷新。

假设

我假设本文的读者已经了解 ASP.NET Ajax。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Ravs
{
    // Declare a clock class
    [ToolboxData("<{0}:Clock  runat="server">")]
    public class Clock : WebControl
    {
        //Create one TimerControl
        Timer timer = new Timer();
        // Create one label control for click value
        Label clockLabel = new Label();
        // Declare one Updatepanel
        UpdatePanel updatePanel = new UpdatePanel();
        // Now override the Load event of Current Web Control
        protected override void OnLoad(EventArgs e)
        {            
            // Create Ids for Control
            timer.ID = ID + "_tiker";
            clockLabel.ID = ID + "_l";
            // get the contentTemplate Control Instance
            Control controlContainer = updatePanel.ContentTemplateContainer;
            // add Label and timer control in Update Panel
            controlContainer.Controls.Add(clockLabel);
            controlContainer.Controls.Add(timer);
            // Add control Trigger in update panel on Tick Event
            updatePanel.Triggers.Add(new AsyncPostBackTrigger() 
		{ ControlID = timer.ID, EventName = "Tick" });
            updatePanel.ChildrenAsTriggers = true;
            // Set default clock time in label
            clockLabel.Text = DateTime.Now.ToString();
            // Set Interval
            timer.Interval = 1000;
            // Add handler to timer
            timer.Tick += new EventHandler(timer_Tick);

            updatePanel.RenderMode = UpdatePanelRenderMode.Block;
            //Add update panel to the base control collection.
            base.Controls.Add(updatePanel);
        }
        protected override void Render(HtmlTextWriter output)
        {
            base.Render(output);
        }

        void timer_Tick(object sender, EventArgs e)
        {
            // Set current date time in label to move current at each Tick Event
            clockLabel.Text = DateTime.Now.ToString();
        }
    }
}

让我们逐个讨论每个部分

到现在为止我们所看到的。一点文字和几行代码,注释相当详细。那么作为读者,您是否能够理解我想表达的内容?我认为没有。所以现在我不得不摆脱我的懒惰,并与您详细讨论这个问题。所以让我们逐个代码部分并检查它到底做了什么。

创建控件的命名空间

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

我们从 Webcontrol 继承了我们的 Clock 控件,因此默认情况下,我们的控件将包含 WebControl 包含的所有属性和方法。

[ToolboxData("<{0}:Clock  runat="server">")]
public class Clock : WebControl      

控件初始化

要创建此控件,我们需要一个像 TimerLabelUpdatePanel 这样的控件。

  • Timer:将在控件中添加自动触发功能
  • Label:将用于在 web 表单上显示时钟数据
  • UpdatePanel:用于将整个时钟处理转换为异步模式,这样它就不会刷新 web 表单的数据,用户就可以进行他/她的工作,而时钟将继续运行。听起来不错 :)
//Create one TimerControl
Timer timer = new Timer();
// Create one label control for click value
Label clockLabel = new Label();
// Declare one Updatepanel
UpdatePanel updatePanel = new UpdatePanel();
// Now override the Load event of Current Web Control

控件的绑定

正如您所看到的,我们创建了每个控件的动态 Id,这样当我们在同一页面上使用两个计时器控件时,它不应该创建问题。

protected override void OnLoad(EventArgs e)
        {            
            // Create Ids for Control
            timer.ID = ID + "_tiker";
            clockLabel.ID = ID + "_l";

在下面,您可以看到我试图在控件中获取 ContentTemplateContainer 。它是具有 Itemplate 实现的内部控件的实例,我们现在将在其中添加我们的控件。

// get the contentTemplate Control Instance
Control controlContainer = updatePanel.ContentTemplateContainer;
// add Label and timer control in Update Panel
controlContainer.Controls.Add(clockLabel);
controlContainer.Controls.Add(timer);

现在我们已经将所有控件(Timer Label)添加到了 updatepanelcontentpanel 中。所以让我们进入主要部分。现在我们将在 update panel 的控件触发器中添加计时器控件的引用,事件名称为 "Tick",这样每当 Timer 触发其 Tick 事件时,Update panel 就会捕获它并将其作为异步请求。现在我们将在标签中设置默认数据。即当前 DateTime,我们将设置计时器 Interval 属性,(我使用静态 1000,您可以根据需要扩展),以便 Timer 知道何时触发其 tick 事件。现在我们需要做的最后一件事是为计时器创建一个事件,就是这样。

timer.Tick += new EventHandler(timer_Tick); 

之后,将 updatepanel 添加到基控件集合中。

// Add control Trigger in update panel on Tick Event
updatePanel.Triggers.Add(new AsyncPostBackTrigger() 
{ 
ControlID = timer.ID, EventName = "Tick" });
updatePanel.ChildrenAsTriggers = true;
// Set default clock time in label
clockLabel.Text = DateTime.Now.ToString();
// Set Interval
timer.Interval = 1000;
// Add handler to timer
timer.Tick += new EventHandler(timer_Tick);

updatePanel.RenderMode = UpdatePanelRenderMode.Block;
//Add update panel to the base control collection.
base.Controls.Add(updatePanel);
}

在 Tick 事件上设置逻辑

这里我们不需要做太多。只需将当前日期时间值设置为标签

void timer_Tick(object sender, EventArgs e) 
{ 
    // Set current date time in label to move current at each Tick Event 
    clockLabel.Text = DateTime.Now.ToString(); 
} 

注意:关于 Render 方法没有定义,因为我没有做任何事情。

如何使用

编译您的控件类并将其添加到 Toolbox 中,然后将其拖到页面上。它将向您显示正在运行的时钟,而无需刷新页面。我希望您能从中学习一些东西,也许您会想出一些更强大的东西。

关注点

在开发此代码时,我使用 Timer 和更新面板获得了一些更好的想法。我将尽力尽快与大家分享一些新的东西。

历史

  • 2008 年 6 月 2 日:初步发布
© . All rights reserved.