2

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
  • 16,119
  • 28
  • 99
  • 199

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,192
  • 8
  • 55
  • 90
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
  • 104,458
  • 27
  • 176
  • 219
  • 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