3

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?

dragonfly
  • 17,407
  • 30
  • 110
  • 219

2 Answers2

3

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);

Atanas Korchev
  • 30,562
  • 8
  • 59
  • 93
0

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

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
  • 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 May 12 '10 at 13:01
  • Ok thanks. However... What if I want to add HTML code, not java script ? :)) – dragonfly May 12 '10 at 13:26