When is the latest you can call Page.ClientScript.RegisterClientScriptBlock?

I need to output some JavaScript in WebControl based on some processing and some properties that the user can set, doing this when the page loads, will be early.

When is the last time I can call RegisterClientScriptBlock and still have its output on the page?

+4
source share
4 answers

Onprerer

or, if you override Render .... before calling base.Render

+3
source

An old question, but I recently dealt with this, therefore, to give Tim an answer to clarify and clarify a bit of misinformation:

If you use RegisterClientScriptBlock, as you ask, your scripts will be output during ClientScriptManager.RenderClientScriptBlocks, which is called during Page.BeginFormRender, but it is actually called by the form, not the page itself.

Here's the sequence:

  • Page.ProcessRequestMain (when it comes to the rendering section) calls
  • (base class of the page) Control.RenderControl, which calls
  • Control.RenderChildren, which iterates over all child controls and ultimately calls
  • HtmlForm.RenderControl, which calls
  • The HtmlForm.RenderChildren we care about

From the reflector:

protected internal override void RenderChildren(HtmlTextWriter writer) { Page page = this.Page; if (page != null) { page.OnFormRender(); page.BeginFormRender(writer, this.UniqueID); } base.RenderChildren(writer); if (page != null) { page.EndFormRender(writer, this.UniqueID); page.OnFormPostRender(); } } 

Pay attention to the calls to the .BeginFormRender page and page.EndFormRender page. Between them, the form calls its base.RenderChildren, which ultimately will call the Render method in the user control. Therefore, to be true to your original question, you cannot interact with a portion of the ClientScriptBlocks scripts at any time during any Render control sequence, as they have already been passed to the Response stream. You can add scripts to this block during the Render sequence if you are in the Render method before you call base.Render, as Tim mentions, but this does not work in any type of child control.

If the Render sequence is all you have to work with (this is the situation I'm in), you can use ClientScript.RegisterStartupScript while controlling the Render, since RenderClientStartupScripts is called during the page. The EndFormRender that occurs after your controls are processed, as you can see in the above code.

+6
source

Logically, your startup script should be displayed as well as registered on the page, so the Page_PreRender event seems to be a good bet. After that, the HTML and script for the page are "locked."

+1
source

Even on the main page, you can call it during PreRender. Each Render control function is called after the PreRender main page, so the Render function will be a safe place.

+1
source

All Articles