开发者

ASP.NET: Appending to HTTP response

开发者 https://www.devze.com 2022-12-12 21:24 出处:网络
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?

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", 开发者_StackOverflowthis.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.


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.


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


I haven't tried this, but I would guess that you are executing the write in the wrong stage of the .NET lifecycle. Page_Load happens prior to any content being rendered, so your Write() will insert text at the top of the page. I'm guessing you want to do this in PreRender:

"Use [PreRender] to make final changes to the contents of the page or its controls before the rendering stage begins."

https://msdn.microsoft.com/en-us/library/ms178472.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消