Reputation: 57
I have the following BasePage
class which all pages on the site inherit directly or via a subclass. I am overriding the Render
method so it outputs a script on every page of the site. The code currently writes the script after the closing /HTML tag.
public class BasePage : Page
{
....
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
base.Render(writer);
Response.Write("<Script>custom</script>");
}
}
Subclass example:
public class AdminPage : BasePage {}
How can I get this to write the script before the closing /BODY tag or /FORM tag? I've tried different variations of RegisterStartUpScript
but none of them work globally, ie, I found many cases where the script would not render at all, so I've fallen back to using Response.Write
to guarantee it would render the script.
Upvotes: 0
Views: 1170
Reputation: 56849
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.
Upvotes: 0
Reputation: 13600
Your method accepts the writer
. You'd have to use that to write to the stream, not using Response
object.
However, I believe you should do this using a (separate? inherited?) MasterPage, not injecting via C#. It's much more transparent and much, much easier ;)
Upvotes: 1