ASP.NET: Register in the header
NOTE: This script is useful for .NET 1.1 only. For .NET 2.0 you can simply create a master page, add a literal in the
<head> section and expose a method to add information to the literal (you may still want to use a hashtable like in the code snippet).
When you want to register client-side JavaScript in ASP.NET Microsoft has
provided two methods of the Page object
RegisterClientScriptBlock and
RegisterStartupScript. These methods will place any text you
want at the top, and bottom of the <BODY> </BODY> tags,
respectively. However I've found that it is useful to render JavaScript in the
header, between the <HEAD> </HEAD> tags. There are a few ways to
accomplish this.
Quick And Dirty Solution The quick
and dirty solution is to add a 'Literal' web control in the header, set it to
runat the server, and then write text to it. This is effective as a simple
workaround, but it doesn't handle more complex situations.
WebForm1.aspx
<html>
<head>
<asp:Literal id="header"
runat="server"></asp:Literal>
</head>
<body>
The content of your web page.
</body>
</html>
WebForm1.aspx.cs (Codebehind)
private
void Page_Load(object sender, System.EventArgs e)
{
header.Text = "<script
language='javascript'>" +
"alert('Sample JavaScript');</script>";
}
A More Robust Approach The
more robust approach mimics the functionality of the methods implemented by
Microsoft. Using a base class to define your web pages, you can implement a
keyed system which will allow you to register many scripts, and reduce the risk
of registering duplicate code. This implementation is particularly useful for
UserControls. With it, you can have all sorts of complex UserControl designs,
and be able to register their respective JavaScripts without worrying about
duplicate or conflicting code.
The source code below provides an
implementation of the base class using this approach, as well as samples of how
to use the base class. The comments in the base class are ample, and should be
sufficient to understand the approach taken.