I’ve been twittering about that I enabled Visual Studio to nest .css and .js files under a user control just like its .ascx.cs file is. That received some attention from people that wanted to know how to do it, so here it is.
If we can group some of the resources used by a user control together with the user control itself, then we can think of those controls as components and easily move them around – even between projects and solutions because they are self contained.
We can take it a step further and automatically add the .css and .js files bundled with the user control to the page’s head section at runtime. This is done very simply by creating a base class for the user control and add a bit of logic to it. Some user controls are used more than once per page, so it is important to only add the resources once per page. The following base class handles that as well.
public class BaseUserControl : UserControl
/// Raises the <see cref="E:System.Web.UI.Control.Load"></see> event.
/// <param name="e">The <see cref="T:System.EventArgs"></see> object that contains the event data.</param>
protected override void OnLoad(EventArgs e)
/// Adds the related resources belonging to the user control.
protected virtual void AddRelatedResources()
if (Context.Items[AppRelativeVirtualPath] == null)
if (Cache[AppRelativeVirtualPath] == null)
string cache = ((string)Cache[AppRelativeVirtualPath]);
AddStylesheet(AppRelativeVirtualPath + ".css");
Context.Items[AppRelativeVirtualPath] = 1;
/// Examines the location for related resources matching the extension.
/// <param name="extension">The file extension to look for.</param>
private void ExamineLocation(string extension)
string stylesheet = Server.MapPath(AppRelativeVirtualPath + extension);
Cache[AppRelativeVirtualPath] += extension;
Cache[AppRelativeVirtualPath] += string.Empty;
/// Adds the stylesheet to the head element of the page.
/// <param name="relativePath">The relative path of the stylesheet.</param>
protected virtual void AddStylesheet(string relativePath)
HtmlLink link = new HtmlLink();
link.Href = VirtualPathUtility.ToAbsolute(relativePath);
link.Attributes["type"] = "text/css";
link.Attributes["rel"] = "stylesheet";
HtmlGenericControl script = new HtmlGenericControl("script");
script.Attributes["src"] = VirtualPathUtility.ToAbsolute(relativePath);
The zip file below contains the base class for user controls as well as a .reg file that will enable Visual Studio to nest .css and .js file under .ascx files. Just double click the .reg file and then place the BaseUserControl.cs in the App_Code folder. You will need to restart Visual Studio after running the .reg file.
The .reg file has only been tested in Visual Studio 2005, but I think if you open it in Notepad you just need to change the version number from 8.0 to 9.0 to make it work in Visual Studio 2008.