views:

43

answers:

2

Hi,

Just before (or during) rendering page I would like to append a piece of code (java script). However when I try to add new LiteralControl via Page.Controls property I get an error:

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

How to get round that issue?

A: 

You can just add the LiteralControl to your markup and set its Text property from code-behind.

EDIT:

Another (and probably more correct) option is to use ScriptManager.RegisterClientScriptBlock

klausbyskov
Unfortunately it won't work: I have a BasePage class which inherits from Page class. And I want to do it in my base class (I don't use master pages though).
dragonfly
@dragonfly I have updated my answer.
klausbyskov
Ok thanks. However... What if I want to add HTML code, not java script ? :))
dragonfly
+1  A: 

To avoid that problem do the following:

  1. Add a <asp:Placeholder id="Placeholder1" runat="server" /> control in your ASPX
  2. In code behind add the control to the Controls collection of that placeholder:

    Placeholder1.Controls.Add(myControl);

korchev