OdeToCode IC Logo

ASP.NET 2.0 User Controls in App_Code

Saturday, October 1, 2005

Here is a tip I picked up at the MVP summit from ASP.NET team member Simon Calvert.

You can place a user control file in App_Code, as long as the .ascx uses inline code. The user control will compile into the App_Code assembly. Instead of using LoadControl with a virtual path parameter, you can use the overloaded version accepting a Type parameter.

As an example, here is the contents of MyUserControl.ascx. Place the file in the App_Code directory.

<%@ Control Language="C#" ClassName="MyUserControl" %>

 

<script runat="server">

 

  protected override void OnLoad(EventArgs e)

  {

    base.OnLoad(e);

    Label.Text = "Bonjour!";

  }   

 

</script>

<asp:Label runat="server" ID="Label" />

Here is the code for a web form that dynamically loads the control.

using System;

using ASP;

 

public partial class _Default : System.Web.UI.Page

{

    protected override void OnInit(EventArgs e)

    {

        base.OnInit(e);

 

        MyUserControl c;

        c = LoadControl(typeof(MyUserControl), null)

            as MyUserControl;

 

        if (c != null)

        {

            Controls.Add(c);

        }

    }

}

Note: No @ Reference directive was required in the .aspx file.

Why is this interesting?

I was conversing with Shawn Wildermuth, and Shawn is unhappy with the solutions needed to make types visible in the ASP.NET 2.0 compilation model, solutions like using @ Reference and stubs. Shawn is not the only one. The above solution is easy if you don’t mind using the App_Code directory. The user control type will be visible to both the App_Code assembly and all web form assemblies.