Nov
13
2006
Javascript include from ASP.NET server control
Posted by admin under
Controls
In ASP.NET 2.0 the Page object has a Header property - which contains a Controls collection. This is good news since it makes it possible to (easily) inject a <script type="text/javascript" src="whatever"> into the <head></head> section of the resulting HTML page.
You can - for example from the code of your custom server control - add a htmlgeneric control to the containing page header control like this:
string sInclude = "~/specialincludes/blabla.js";
sInclude = ResolveUrl( sInclude );
HtmlGenericControl Include = new HtmlGenericControl("script");
Include.Attributes.Add("type", "text/javascript");
Include.Attributes.Add("src", sInclude);
this.Page.Header.Controls.Add(Include);
and that would make the resulting html code look like this:
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" src="/thesite/specialincludes/blabla.js"></script>
I will later present a more complete example using this technique, for now I just present the way of doing it.