Dynamically Add UserControls based on the Request URL

You have a data-driven site and you like to keep the number of .aspx files to a minimum, so you opt for UserControls. Ok cool!

user controls are hot!Something you can do to be more dynamic-y is to name a UserControl the same as the requesting url, then check its existence on PageLoad. If it exists, load it into an asp:PlaceHolder control (or some other control). This can help keep your site more modular, and perhaps increase the chances that you'll reuse a UserControl in another project...or not.

Here the UserControls are stored in the /UserControls/dynamic folder on my site.

In your aspx page, we make an asp:PlaceHolder...

<asp:PlaceHolder ID="PHUserControls" runat="server"></asp:PlaceHolder>

And in code behind, on PageLoad... we make the path of the UserControl and see if it exists. If it does, we add it to the placeholder.

string path = AppDomain.CurrentDomain.BaseDirectory + "UserControls\\dynamic\\" + PageUrl + ".ascx";
if (File.Exists(path))
{
Control c = LoadControl("~/UserControls/dynamic/" + PageUrl + ".ascx");
PHUserControls.Controls.Add(c);
}

About Brian


Brian Canzanella brings you nifty tips and tricks for most things .NET. read more...

Readers / Stuff