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.
Comments
Heres what I did. I added a user control (Quotes.ascx), lets say in the App_Code section.
In the aspx page, I am trying to reference the control as follows.
Dim q As Quotes
But it keeps saying Quotes is undefined. Note as per your writing, I didn't include a "register" in the aspx page.
I have not tried express but I wonder if this was a capability added to the release candidate that was not in beta 2. Are you trying beta 2? I used the RC.
Still, November soon, so we'll all have the access to the release build!
It'll be worth checking this out though as another option for WUC's
Thanks!
You can certainly inherit from a class in App_Code or a class library.
The only way to put the .ascx itself in App_Code is to use inline code.
Either I go back to <%Reference Control or I put Content in a namespace, I guess.
The type or namespace name 'MyUserControl' could not be found (are you missing a using directive or an assembly reference?)
VS recognizes the control in intellisence and I can run the page by creating a virtual directory to my website folder, but it won't compile for me.
Any help would be greatly appreciated.
Jeff