It’s often troublesome to link to JavaScript and CSS files in ASP.NET pages when the desired files can’t easily be accessed from the current path. For example, when setting up SyntaxHighlighter on this site, it seemed like good practice to not include the JS and CSS files in the BlogEngine.NET theme directory, but in the root of the application. After all, any theme should be able to access these files. ASP.NET provides the root operator for just this purpose. Unfortunately, it doesn't work with client-side markup, and there are no server-side controls for styles or scripts. One solution is to resolve the path manually:
<script type="text/javascript" src='<%= ResolveUrl("~/path/to/script.js") %>'></script>
...but that's not particularly clean. A better way is to create a control specifically for this purpose, so one can do the following:
<controls:JavaScript Src="~/path/to/script.js" runat="server" />
<controls:Css Href="~/path/to/style.css" runat="server" />
The source for these controls is really simple. The JS and CSS controls contain the Src and Href properties to be similar to their respective markup. The JS control:
public class JavaScript : Control
{
public String Src { get; set; }
protected override void Render(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
writer.AddAttribute(HtmlTextWriterAttribute.Src, ResolveUrl(Src));
writer.RenderBeginTag(HtmlTextWriterTag.Script);
writer.RenderEndTag();
}
}
And the CSS control:
public class Css : Control
{
public String Href { get; set; }
protected override void Render(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet");
writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/css");
writer.AddAttribute(HtmlTextWriterAttribute.Href, ResolveUrl(Href));
writer.RenderBeginTag(HtmlTextWriterTag.Link);
writer.RenderEndTag();
}
}