ASP.net Tip: Register User/Custom Controls globally

June 15, 2010 by C#   ASP.NET  

Generally when adding/dropping an user/custom control to a page, we use/used to use the @Register directive to reference our controls (or the IDE did it for you), like this:

...
<%@ Register Src="Controls/SomeControl.ascx" TagName="SomeControl" TagPrefix="cstruter" %>
<%@ Register Assembly="ServerControl" Namespace="ServerControl" TagPrefix="somevendor" %>
...
<body>
    <form id="form1" runat="server">
    <div>
        <cstruter:SomeControl ID="SomeControl1" runat="server" />
        <somevendor:ServerControl1 ID="ServerControl11" runat="server" />
    </div>
    </form>
...

Now this is bit of a dodgy situation, since whenever we want to use these controls we need to add the directive above each and every page - which obviously is a bit of a bad idea.

It would make a lot more sense to register these controls somewhere globally - which is exactly what we can do since ASP.net 2.0, observe:
<system.web>
...
    <pages>
      <controls>
	  ...
        <add src="~/Controls/SomeControl.ascx" tagName="SomeControl" tagPrefix="cstruter" />
        <add assembly="ServerControl" namespace="ServerControl" tagPrefix="somevendor" />
...

Which means we can simply remove the @Register directives from our pages, since the references to our controls are available via the web.config now.

Note: If you look closely you will notice I added the tilde sign infront of the path where the usercontrol in the example resides - which resolves the path to the root of the web application.


Leave a Comment