views:

80

answers:

2

I have a Page.aspx. I would like to inject a <script> tag into the response stream of Page.aspx, after it has finished writing its output. How could I do this form within the codebehind of Page?

If I do this:

    protected void Page_Load(object sender, EventArgs e)
    {
        this.ClientScript.RegisterClientScriptInclude
                    ("dfasfds", this.Request.Path.Replace(".aspx", ".js"));
    }

Then the script appears in the HTML response, but not at the end.

If I do this:

    protected void Page_Load(object sender, EventArgs e)
    {
        this.Response.Flush();
        this.Response.Write(.../*my javascript*/...);
    }

Then the <script> tag appears at the very beginnning of the document, on the first line.

A: 
string key = "MyScript";
string src = Request.Path.Replace(".aspx", ".js"); 
string script = "<script type=\"text/javascript\" src=\"" + src + "\"></script>";
ClientScript.RegisterStartupScript(GetType(), key, script);
ChaosPandion
A: 

The contents of your page aren't written into the Response stream until the Render phase. If you call Response.Flush() in Page_Load(), there's nothing there yet to flush.

Instead, you could try calling Response.Write() from the Page_Unload() event; I'm pretty sure the Response stream is still alive at that point.

However, the result of doing this would be to have your script come after the tag. It would be more correct to do something like use a Master Page, and have the script tag in the markup there, or possibly insert it using a user control.

RickNZ