Solutions2
You can put JavaScript near the end of your page using the Page.CleintScript.RegisterStartupScript method. This method places the JavaScript at the end of the form tag.
protected void Page_Load(object sender, EventArgs e)
{
this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(),
"MyJavaScript", "custom", true);
}
The first argument must be the type of the current page (note that it will sometimes fail if it is not). The second is a key that uniquely identifies this script on the page (so you can add/update more than one). The third argument is a string that contains your code (you can use a StringBuilder to make that part easier). The last argument (if true) makes the framework include the script tags so you don't have to put them into your code string.
It works fine from a base class as long as you pass the System.Web.UI.Page object to a method defined in the base class.
// In base class
protected void LoadJavaScript(System.Web.UI.Page page)
{
string key = "MyJavaScript";
if (page.ClientScript.IsStartupScriptRegistered(key))
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("alert('hello');");
page.ClientScript.RegisterStartupScript(page.GetType(),
key, sb.ToString(), true);
}
}
// In subclass
protected void Page_Load(object sender, EventArgs e)
{
this.LoadJavaScript(this.Page);
}
Per MSDN, you also need to ensure you have a unique key for each piece of JavaScript you register.
A startup script is uniquely identified by its key and its type. Scripts with the same key and type are considered duplicates. Only one script with a given type and key pair can be registered with the page. Attempting to register a script that is already registered does not create a duplicate of the script.