Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET: Register multiple controls at once via namespace?

Is it possible to register a complete namespace of usercontrols in an aspx-File, instead of each control seperately?

I have created a bunch of usercontrols and collected them into an own namespace "MyWebControls", like this:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="LevelFilter.ascx.cs" Inherits="MyWebControls.LevelFilter" %>

Codebehind:

namespace MyWebControls
{
    public partial class LevelFilter : System.Web.UI.UserControl
    {
       ...
    }
}

What I tried now to include them in my pages (and what did not work):

<%@ Register Namespace="MyWebControls" TagPrefix="ucs" %>
...
<ucs:LevelFilter />

Is there any way to do this? Apparently it works with external assemblies like AjaxControlToolkit, so I guess this should be possible.

I am using ASP.NET 4.0.

like image 521
magnattic Avatar asked Mar 03 '11 16:03

magnattic


2 Answers

With user controls there's just no way to do this :-( You can only use the namespace and assembly attributes to bring in controls from an assembly, and usercontrols don't export to a separate assembly very well (I suspect it's to do with the way user controls have separate code and markup).

If you really have your heart set on this you'll need to convert your user controls to server controls - there's a piece on the CodeProject here that looks like it might offer some shortcuts to doing this.

Otherwise my best suggestion is to register all your user controls centrally in your web.config so they are available to all your pages. To do this, in your web.config under system.web/pages/controls add each of them like this:

<add tagprefix="ucs" tagname="MyFirstControl" src="~/UserControls/MyFirstControl.ascx" />
like image 52
PhilPursglove Avatar answered Oct 19 '22 21:10

PhilPursglove


For Global Registration

In your web.config under system.web/pages/controls

<pages>
  <controls>
    <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.
    <add tagPrefix="ucs" namespace="MyWebControls" assembly="MyAssemblyName" />
  </controls>

Documentation for this part of your web.config in .NET 4.0 is available at msdn.microsoft.com/en-us/library/ms164640.aspx .

For Local Registration

The reason your @Register directive is not working is that you have omitted the assembly attribute. The line should look like

<%@ Register TagPrefix="ucs" Namespace="MyWebControls" Assembly="MyAssemblyName" %>

Please see this related post for details.

like image 22
smartcaveman Avatar answered Oct 19 '22 22:10

smartcaveman