How to output HTML at the end of a WebForm from code?
With all this client-side activity that's going on lately, there's one particular need I've seen arise repeatedly. It is often useful to output contents at the end of a page (or at the end of the form, at least). The reasons why you would want to render contents not in the current position in the stream of the rendering page but at the end are diverse. One reason could be that you want only one instance of that contents on the page no matter how many controls require it. Another could be that you want controls to be able to add to a big chunk of data that you want to output in one piece at the end (that's a need we had in Atlas).
Well, if you happen to have that particular need, there's one API that will help you immensely despite its name which only reflects its original intention:
Page.ClientScript.RegisterStartupScript(
typeof(YourControlOrPageType),"KeyUniqueToThisBlock",
"<div>This will be rendered before </form>.</div>"); This call will put your HTML chunk aside while it's rendering the end of the form and will ouput it just before the </form> tag. The key parameter ensures that only one instance of this HTML fragment will be rendered no matter how many times the call was made. You can make this call from anywhere, although it's usually done from PreRender. Render is OK for this client script registration if you're in a control that can only render in a form (it's too late for other client script register APIs, and it's only OK from page if you call the base method after it.). There must be a <form runat="server"> on the page for this to work.
Finally, I think I should mention that the order in which blocks are registered is the order in which the blocks will be output.
(thanks to Chris Sharpe for this post idea and the previous one)
UPDATE: Peter Blum just pointed me to another use of this idea. If you need to output some kind of popup as part of a control's rendering, the popup really doesn't belong next or inside the rendering of the main part of the control. Furthermore, it may be rendered as a DIV, which is invalid inside a SPAN or other inline elements, so it has to be put someplace neutral like the end of the form to ensure XHTML compliance. This little trick is perfect for this use.