15th Jul, 2007

Tips and Tricks: Registering Custom Controls and User Controls in ASP.NET web.config

Last week I was trying to reuse some parts of an existent ASP.NET application and was quite annoyed with the amount of register directives <%@ Register %>on every aspx page. For those of you who do not know, the registration of custom controls and user controls can be easiliy centralised in the web.config.

So you can achieve this

<%@ Register TagPrefix=”carlo” TagName=”header” Src=”Controls/Header.ascx” %>
<%@ Register TagPrefix=”carlo” TagName=”footer” Src=”Controls/Footer.ascx” %>
<%@ Register TagPrefix=”MyControlAssembly” Assembly=”
MyControlAssembly %>

by adding a <pages> element in <system.web> in the web.config as following:

<?xml version=”1.0″?>
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix=”carlo” src=”~/Controls/Header.ascx” tagName=”header”/>
<
add tagPrefix=”carlo” src=”~/Controls/Footer.ascx” tagName=”footer”/>
<
add tagPrefix=”MyControlAssembly”
assembly=”MyControlAssembly”/>
</
controls>
</pages>
</system.web>
</configuration>

I would recommend using this feature in ASP.NET 2.0 as opposed to using register directives on every page. This way you can be sure that the tag prefixes will be consistent throughout the application.

You can then add the referenced controls on the aspx pages normally as following:

<html>
<body>
<form id=”form1″ runat=”server”>
<carlo:header ID=”MyHeader” runat=”server” />
</
form>
</body>
</html>

Have you ever been to Malta? All you need to know is a click away! Malta Travel Guide, Bargain Accommodation in Malta, Malta Hotels

Leave a response

Your response:

Categories