如何在 ASP.NET 中开发一个简单的垂直文本滚动自定义服务器控件






4.42/5 (5投票s)
关于如何在 ASP.NET 2.0 中创建自定义服务器控件的分步指南

引言
几年前,我一直在寻找一个简单的文本滚动应用程序来替换我基于 Java 的文本滚动应用程序,并在 dynamicdrive.com 上找到了名为 Cross Browser marquee II 的应用程序。我对其进行了修改以满足我的需求。我对滚动程序的主要修改是添加了两个按钮,用于控制垂直滚动内容的流动。最近,我在 Google 上快速搜索了一下,发现仍有(50 多个)网站在使用此应用程序。以下是其中几个。
查看一下。
- http://cherryle.win.aplus.net/index.asp
- http://www.hydroqual.com
- http://www.sabugacenter.com
- http://www.ehub.si
- http://www.globalnews-indonesia.com
- http://www.mmtv.co.za/index.htm
- http://www.opcfoundation.org
现在,我已将此应用程序转换为 ASP.NET 自定义服务器控件。这样,ASP.NET 开发人员就可以将其拖放到页面上,而无需在 Web 应用程序之间进行复制粘贴。以下是我如何实现这一目标的逐步教程。希望这个教程能给某些人带来关于如何创建自定义服务器控件的想法。
下载原始应用程序/脚本
注意
我将 cmarquee2.htm 页面分解为三个不同的部分,即 **样式表**、**JavaScript** 和 **静态 HTML 元素/标签**。
创建类库
- 打开 VS 2005/2008。转到“文件”、“新建”、“项目”,选择“Visual C#”下的“类库”模板,并填写所需字段。
- 将 class1.cs 重命名为 TextScroller.cs。
添加样式表
右键单击项目,选择“添加”、“新建项”、“Visual C# 项目项”,从可用模板中选择“样式表”。我将其命名为 TextScroller.css。将 cmarquee2.htm 中的所有样式表提取到 TextScroller.css 中。
添加 JavaScript
右键单击项目,选择“添加”、“新建项”、“Visual C# 项目项”,从可用模板中选择“Jscript”。我将其命名为 TextScroller.js。将 cmarquee2.htm 中的所有 JavaScript 提取到 TextScroller.js 中。

添加新文件夹
右键单击 MyTextScroller
项目,选择“添加”、“新建文件夹”,将文件夹重命名为 images。将所有图像放入此文件夹。
添加 System.Web 引用
右键单击 MyTextScroller
项目,选择“添加引用”。在 .NET 选项卡中,找到 System.Web
组件名称,选中它,然后单击“确定”。

检查点
如果按照上述所有步骤正确操作,项目的结构应该如下图所示。

嵌入资源
右键单击其中一张图片,选择“属性”,然后将“生成操作”的值从“内容”更改为“嵌入资源”。对所有其他图片重复此步骤。

对 JavaScript 和样式表重复上述步骤。
双击 AssemblyInfo.cs。将以下内容添加到文件末尾。
[assembly: System.Web.UI.WebResource("MyTextScroller.TextScroller.css", "text/css")]
[assembly: System.Web.UI.WebResource
("MyTextScroller.TextScroller.js", "text/javascript")]
[assembly: System.Web.UI.WebResource
("MyTextScroller.images.nav-arrow-down-hover.gif", "image/gif")]
[assembly: System.Web.UI.WebResource
("MyTextScroller.images.nav-arrow-down.gif", "image/gif")]
[assembly: System.Web.UI.WebResource
("MyTextScroller.images.nav-arrow-up-hover.gif", "image/gif")]
[assembly: System.Web.UI.WebResource
("MyTextScroller.images.nav-arrow-up.gif", "image/gif")]
注意

语法
[assembly: System.Web.UI.WebResource
("Default Namespace.File Location.File Name", "Type")]
示例 1
我的默认命名空间是 MyTextScroller
。
我的 JavaScript 文件名为 TextScroller.js,我最终会在 AssemblyInfo.cs 中得到这一行。
[assembly: System.Web.UI.WebResource
("MyTextScroller.TextScroller.js", "text/javascript")]>
示例 2
我的默认命名空间是 MyTextScroller
。
我所有的图像都在 images 文件夹中。
我的图像名称是 nav-arrow-down-hover.gif,我最终会在 AssemblyInfo.cs 中得到这一行。
[assembly: System.Web.UI.WebResource
("MyTextScroller.images.nav-arrow-down.gif", "image/gif")]
TextScroller.cs
TextScroller.cs 将包含 cmarquee2.htm 中的所有 static
HTML 元素。请查看代码,它相当直观。以下是简要说明。
添加设计时属性以提供自定义元数据,这些元数据将在设计时用于在可视化设计器中显示控件。
namespace MyTextScroller
{
[ AspNetHostingPermission(SecurityAction.Demand,
Level = AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level = AspNetHostingPermissionLevel.Minimal),
ParseChildren(true, "innerHTML"),
DefaultProperty("innerHTML"),
ToolboxData("<{0}:TextScroller runat=\"server\"> ") ]
public class TextScroller : WebControl, INamingContainer
{
其他阅读/信息
ToolboxData
属性指定当 TextScroller
控件从 Toolbox
拖到设计时页面上时生成的默认标记。
// 调整 div 宽度和高度并设置 div 的 innerHTML 的属性
#region Public Properties
private Unit width = Unit.Pixel(260);
public override Unit Width
{
get { return width; }
set { EnsureChildControls(); width = value; }
}
private Unit height = Unit.Pixel(160);
public override Unit Height
{
get { return height; }
set { EnsureChildControls(); height = value; }
}
//property to set the content of the Text Scroller
private string _innerHTML = "Your Content here";
[ Browsable(true), //display this property in designer
Category("Appearance"),
DefaultValue("Your Content Here"),
Description("The Content to Display."),
Localizable(true),
PersistenceMode(PersistenceMode.InnerDefaultProperty) ]
public virtual string innerHTML
{
get
{
return _innerHTML;
}
set
{
EnsureChildControls(); _innerHTML = value;
}
}
#endregion
使用 ASP.NET 2.0 中的 Web 资源
示例 - 图像
Image myImage = new Image();
ClientScriptManager cs = Page.ClientScript;
Type rsType = this.GetType();
myImage.ImageUrl = cs.GetWebResourceUrl
(rsType, "MyTextScroller.images.nav-arrow-up.gif")
示例 - JavaScript
Type rsType = this.GetType();
this.Page.ClientScript.RegisterClientScriptInclude(
rsType, "TextScroller_Script_Name",
Page.ClientScript.GetWebResourceUrl(rsType, " MyTextScroller.TextScroller.js"));
示例 - 样式表
Type rsType = this.GetType();
string csslink = "<link rel='stylesheet' type='text/css' href='" +
Page.ClientScript.GetWebResourceUrl
(rsType, "MyTextScroller.TextScroller.css") + "' />";
LiteralControl include = new LiteralControl(csslink);
this.Page.Header.Controls.Add(include);
// 使用嵌入的 JavaScript 和样式表
protected override void OnInit(EventArgs e)
{
//Get the name of the Web Resource.
base.OnInit(e);
this.Page.ClientScript.RegisterClientScriptInclude(
this.GetType(), "TextScroller",
Page.ClientScript.GetWebResourceUrl(this.GetType(),
"Scroller.TextScroller.js"));
// create the style sheet control and put it in the document header
string csslink = @"<link rel='stylesheet' type='text/css' href='" +
Page.ClientScript.GetWebResourceUrl(this.GetType(),
"Scroller.TextScroller.css") + "' />";
LiteralControl include = new LiteralControl(csslink);
this.Page.Header.Controls.Add(include);
}
// 将输出写入 cmarquee2.htm 页面中的页面
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
}
protected override void Render(HtmlTextWriter output)
{
EnsureChildControls();
output.Write(GenerateDiv());
}
//create all the HTML Tag elements
private string GenerateDiv()
{
StringBuilder b = new StringBuilder();
ClientScriptManager cs = Page.ClientScript;
Type rsType = this.GetType();
b.Append("<div style=\"width:");
b.Append(width.Value);
//see attached code ...
....
return b.ToString();
}
protected override void CreateChildControls()
{
Controls.Clear();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
}
}
个性化控件:为控件添加自定义工具箱图标
- 从以下任一链接创建一个图标。此服务是免费的。
- 你的类名是什么?例如,我的类名是
TextScroller
。public class TextScroller : WebControl, INamingContainer
然后我将图标命名为 TextScroller.ico。将其放在项目根目录下,并将“生成操作”更改为 **嵌入资源**。

将控件添加到工具箱
- 转到“视图”、“工具箱”,右键单击工具箱中的任意位置,选择“添加选项卡”,我将其命名为
MyTextScroller
。 - 右键单击
MyTextScroller
,选择“选择项”,在“.NET Framework 组件”选项卡中,单击“浏览”,找到 MyTextScroller.dll,然后单击“确定”。 - 您应该会在
Toolbox
上看到类似这样的内容。

如何测试?/ 使用代码
添加引用
- 右键单击解决方案,选择“添加”、“新建网站”,选择“ASP.NET 网站”/“支持 AJAX 的 ASP.NET 网站”。
- 右键单击
TestMyTextScroller
,选择“添加引用”,在“项目”选项卡中,选择MyTextScroller
项目,然后单击“确定”。
将 TextScroller
从 Toolbox
拖到 Default.aspx。尝试以下操作之一:
<cc1:TextScroller ID="TextScroller1" runat="server" Height="100px">
My test content here.
My Blog
More text here….
</cc1:TextScroller>
或者
protected void Page_Load(object sender, EventArgs e)
{
TextScrollerContent();
}
internal void TextScrollerContent()
{
StringBuilder sbContent = new StringBuilder(string.Empty);
sbContent.Append("My test content here. <br />");
sbContent.Append("<a href=\"http://blog.ysatech.com\">My Blog <br />");
sbContent.Append("More text here…");
TextScroller1.innerHTML = sbContent.ToString();
}
您应该会看到类似以下的显示。

关注点
不要使用任何未知来源的、嵌入了 JavaScript 的自定义服务器控件。请仔细检查所有 JavaScript,确保其中没有嵌入任何潜在的恶意脚本。
下一步改进
- 支持多个实例,目前此版本只能在一个页面上使用一个
TextScroller
实例。 - 允许用户在设计时更改图像按钮。
结论
这是本文中涵盖的项目列表:
- 如何创建自定义服务器控件
- 如何嵌入资源
- 如何访问嵌入的资源
- 如何包含自定义工具箱图标
- 如何测试新控件
参考文献
- http://aspalliance.com/726
- http://www.dynamicdrive.com/dynamicindex2/cmarquee2.htm
- https://codeproject.org.cn/
- http://msdn.microsoft.com/en-us/library/system.web.ui.control.ensurechildcontrols.aspx
- http://msdn.microsoft.com/en-us/library/system.web.aspnethostingpermission.aspx
- http://ondotnet.com/pub/a/dotnet/excerpt/progaspdotnet_14/index2.html
- http://msdn.microsoft.com/en-us/library/system.web.ui.parsechildrenattribute.aspx
历史
- 2009 年 7 月 23 日:首次发布