ASP.NET 2.0 使得控件声明极其干净而且管理起来极其容易。不用在你的页面上重复这些声明,只要在你的应用的web.config 文件的新的 pages->controls 部分声明一次即可:
<?xml version="1.0"?>
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix="scottgu" src="~/Controls/Header.ascx" tagName="header"/>
<add tagPrefix="scottgu" src="~/Controls/Footer.ascx" tagName="footer"/>
<add tagPrefix="ControlVendor" assembly="ControlVendorAssembly"/>
</controls>
</pages>
</system.web>
</configuration>
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix="scottgu" src="~/Controls/Header.ascx" tagName="header"/>
<add tagPrefix="scottgu" src="~/Controls/Footer.ascx" tagName="footer"/>
<add tagPrefix="ControlVendor" assembly="ControlVendorAssembly"/>
</controls>
</pages>
</system.web>
</configuration>
你可以用这种方式同时声明用户控件和编译好的自定义控件。当你使用这个技巧时,Visual Studio是完全支持这两者的,而且 VS 2005 Web Site 项目 和 VS 2005 Web Application 项目也都支持这两者。Visual Studio会在设计器里以所见即所得(WYSIWYG)模式显示这些控件,也会在后台编码文件里提示控件字段的声明。
需要注意的是,上面用户控件中“~”句法的使用。对那些不熟悉这个符号的人,ASP.NET中“~”符号意思是“从应用的根路径来定位”,它提供了一个很好的方法来避免在你的编码里到处使用“..\”。在web.config文件里声明用户控件时,你总是应该使用它,因为页面也许会使用在不同子目录里的控件,所以你应该总是始终如一地从应用的根路径开始定位这些控件。
一旦你在web.config 文件中声明好这些控件后,你就可以在你网站上的任何一个页面,母板页或者用户控件中使用它们了,象这样(不再需要注册指令):
<html>
<body>
<form id="form1" runat="server">
<scottgu:header ID="MyHeader" runat="server" />
</form>
</body>
</html>
<body>
<form id="form1" runat="server">
<scottgu:header ID="MyHeader" runat="server" />
</form>
</body>
</html>
希望本文对你有所帮助,
浙公网安备 33010602011771号