Labels

Monday, March 31, 2008

Register User Controls and Custom Controls in Web.config

Hi,

 

This blog post summarizes a best approach for registering UserControl or Custom Controls.

 

Old Approach:

 

In ASP.NET 1.x, to use both the custom server controls and user controls on a page, required to to add <%@ Register %> directives to the top of pages like so:

 

<%@ Register TagPrefix="scott" TagName="header" Src="Controls/Header.ascx" %>
<%@ Register TagPrefix="scott" TagName="footer" Src="Controls/Footer.ascx" %>
<%@ Register TagPrefix="ControlVendor" Assembly="ControlVendor" %>

<html>
<body>
    <form id="form1" runat="server">
        <scott:header ID="MyHeader" runat="server" />
    </form>
</body>
</html>

 

Note: First two register directives above are for User-Controls (implemented in .ascx files), while the last is for a Custom Control compiled into an assembly .dll file.

 

 

New Approach:

 

ASP.NET 2.0 makes control declarations much cleaner and easier to manage. Instead of duplicating them on all your pages, just declare them once within the new pages->controls section with the web.config file of your application:

 

<?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>

 

Once you register the controls within the web.config file, you can then just use the controls on any page, master-page or user control on your site like so (no registration directives required):

 

<html>
<body>
    <form id="form1" runat="server">
        <scott:header ID="MyHeader" runat="server" />
    </form>
</body>
</html>

 

 

Hope this helps.

 

 

Arun Manglick

 

No comments:

Post a Comment