Wednesday, July 9, 2008

Inserting Dynamic HTML via Code Behind

If you need to insert HTML or any other code into your aspx source code at runtime use an asp:Literal control. The control is placed where the HTML or code should show up:

<asp:Literal runat="server" ID="favIcon" />


Now in the code behind, you can reference the literal and place any code into the literal like so:

favIcon.Text = "<link rel=""shortcut icon"" href=""favicon.ico"" />"


asp:Literal's come in handy when you need to insert code at specific places in your html source. Page.ClientScript.RegisterClientScriptBlock() is a great way to insert JavaScript and other code at run time too, but unfortunately the code is placed on the bottom of the html source where ASP wants it and not where you want it.

This is in no way a replacement for RegisterClientScriptBlock() as this function has its own great benefits for inserting JavaScript.

No comments: