Contact   •   Products   •   Search

Rick Strahl's Web Log

Wind, waves, code and everything in between...
ASP.NET • C# • HTML5 • JavaScript • AngularJs

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


Bummer. I've been mucking around with some more custom databinding that integrates validation into the databinding process. One of the things the control does is automatically add 'notification' icons or error text to the page. The idea is this:

 

  • Control(s) unbind
  • If there are binding errors an Icon or Message is injected into the Control Collection

 

Basically the code looks something like this:

public bool AddBindingError(string ErrorMessage, wwDataBindingItem BindingItem)

{

    // *** Associated control found - add icon and link id

    if (BindingItem.ControlInstance != null)

        this.BindingErrors.Add(new BindingError(ErrorMessage, BindingItem.ControlInstance.ClientID));

    else

    {

        // *** Just set the error message

        this.BindingErrors.Add(new BindingError(ErrorMessage) );

        return false;

    }

 

    BindingItem.BindingErrorMessage = ErrorMessage;

 

    // *** Insert the error text/icon as a literal

    if (this.ShowBindingErrorsOnControls && BindingItem.ControlInstance != null)

    {

        LiteralControl Literal = new LiteralControl(this.GetBindingErrorMessageHtml(BindingItem));

        int CtlIdx = BindingItem.ControlInstance.Parent.Controls.IndexOf(BindingItem.ControlInstance);

        try

        {

            // *** Can't add controls to the Control collection if <%= %> tags are on the page

            BindingItem.ControlInstance.Parent.Controls.AddAt(CtlIdx + 1, Literal);

        }

        catch {;}

    }

 

    return true;

}

 

And it works beautifully in most situations. The literal control creates markup that loads the appropriate image and adds the error text (if configured that way).

 

This all works great until you happen to have some script markup on the page using. For example if the page contains something as simple as this:

 

<%= DateTime.Now    %>

 

The Controls.AddAt() call will fail with:

 

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

 

Now I feel like a complete schmuck to never have run into this before. That's one hell of an assumption to miss about ASP.NET it seems. I have tons of pages where there's <%= %> markup on it. Especially in script code to get the appropariate ClientID:

 

<%= this.txtCompany.ClientID %>

 

Luckily there's a workaround for code like this by using DataBinding expressions instead:

 

<%# this.txtCompany.ClientID %>

 

This works fine for simple expressions. The difference here is that <%= %> expressions are embedded into the ASP.NET output as part of the generated Parse Tree class, whereas the <%# %> expressions are embedded at runtime.

 

Another workaround is to force any script code into the content of a server control and remove it from the Page class or the Content container that you're adding controls to.

 

   <div runat="server">

    <script type="text/javascript">

      function ShowCreditCard()

      {

         var IsPayPal = false;

         for(x=0; x<4; x++ )

         {

                var ctl = $("<%= this.txtCCType.ClientID %>_" + x.toString());

                if (ctl == null)

                     break;

               

                if (ctl.value == "PP" && ctl.checked)

                {

                     IsPayPal = true;

                     break;

                }

         }

        

         var loCC = $("<%= this.trCreditCard.ClientID %>");

         if (loCC == null)

            return;

         var loCC2 = $("<%= this.trCreditCardExpiration.ClientID %>");

 

         if (IsPayPal)

         {

            loCC.style.display = "none";

            loCC2.style.display = "none";

         }           

         else

         {

            loCC.style.display = "";

            loCC2.style.display = "";

         }

      }

</script>

</div>

 

This works as well, although this is also pretty ugly. In my case this is probably the easier solution though, because most of my markup expressions are doing exactly what's happening above: Embedding ClientScript Ids into JavaScript.

 

I still don't see why the control collection can't be modified if there are <% %> blocks on the page. Those blocks are just turned into Response.Write() commands, or raw code blocks. I don't see how this affects the Controls collection that would require this sort of error.

 

In my situation here I was able to get by just switching to <%# %> or wrapping sections with a server tag. Even if that's not an option the above code captures the error and goes on. This means the warning icons don't show up, but the rest of the error handling showing the summary and error control linking etc. all still works.

 

Can anybody think of another more reliable way to inject markup into the page dynamically from outside of the control rendering? In a previous rev of my databinding tools I had custom controls and I simply took over post rendering which was reliable. But this is not so easily done externally… I can think of possibly hooking up the Render method and calling back into my custom control, but man does that seem ugly.

 

Make Donation


Feedback for this Post

 
# Reliably adding Controls or Markup before or after an ASP.NET Control?
by Rick Strahl's WebLog May 28, 2006 @ 1:32pm
Expanding on yesterday's problem with markup script and using Control.Control.Add() I'm trying to find some way to override rendering of a control, from an external control (an Extender in this case). Here are some thoughts, but unfortunately no solutions...
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;).
by Johan Olofsson May 30, 2006 @ 5:30am
Hi Rick!

If you can live with adding a PlaceHolder control to
your aspx-files, then you can modifiy its (the placeholders)
control collection.

Thanks for an interesting blog,
Johan Olofsson
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;).
by Rick Strahl May 30, 2006 @ 12:05pm
Johan, yes any control container would work actually, but this being a generic control using any sort of specific layout doesn't work.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;).
by Milan Negovan May 30, 2006 @ 1:32pm
Deja vu, Rick: I was banging my head against the wall over this just the other day:

http://www.aspnetresources.com/blog/code_blocks_inside_master_pages_cause_trouble.aspx
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;).
by Dennis June 20, 2006 @ 1:22pm
Dude, you are the man. I can not tell you how many times I have had a problem (like this one), done a google search and you had the answer. Thanks for sharing your wisdom!
# Working around Controls.Add() and
by Rick Strahl's WebLog June 20, 2006 @ 4:58pm
A while back I had lamented some issues with Controls.Add() when script tags where on the page. This gets in the way of generic controls that need to dynamically add content to a page. After some thought I decided that injecting the markup with client side JavaScript code generated from the control would do the trick.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;).
by vikram2101 June 21, 2006 @ 5:50pm
thanks. you saved me alot of time.
# Adding Rendering with SetRenderMethodDelegate() - aeh, sort of
by Rick Strahl's WebLog June 23, 2006 @ 10:47pm
I ran into SetRenderMethodDelegate today and was thinking it'd be very useful for injecting HTML into a control. Unfortunately it turns out that the delegate is not fired on all controls as there's a dependency on base.Render() calls which apparently are not made by all controls even the stock controls.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;).
by Mano July 18, 2006 @ 8:31pm
Thanks alot man! I've been pulling my hair over this...
# Tips & Tricks: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Tips & Tricks October 07, 2006 @ 2:00am
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Jeremy Wadsworth October 17, 2006 @ 9:03am
Crap, every time I've come across this error, I've managed to find another way to accomplish whatever I was trying to do. I came across the error again today, and decided to Google it. I have no idea why I didn't Google it before. Thanks for the solution. Great blog as well, this isn't the first time a search engine has brought me to your site.
# More info on why the error occurs
by Rick Strahl October 17, 2006 @ 1:59pm
I have more detailed information on exactly why this error occurs as part of the ASP.NET page rendering here:

http://west-wind.com/WebLog/posts/6148.aspx
# Tips & Tricks: 09/01/2006 - 10/01/2006
by Tips & Tricks November 24, 2006 @ 8:32pm
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Tom Holder January 05, 2007 @ 9:24am
I've experienced the same issue with the .NET RSS Toolkit (which is great - despite this).

I had some code like the following in my head to link a CSS:


The RssHyperLink control was causing it to break because it's trying to add a literal control in to the head for the link.

I solved it by putting in a PlaceHolder property and then putting a placeholder in to my head and then finding all of the rsshyperlink controls and passing it along.

There has to be a better way, but it's fixed it for me.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Tom Holder January 05, 2007 @ 9:25am
Sorry, missed out the code throwing causing the error:

<link rel="stylesheet" type="text/css" href="<%=ResolveUrl("~/css/global.css")%>" media="screen" />
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Rick Strahl January 05, 2007 @ 11:46am
Actually a placeholder control (or a label or literal) all work and that's just fine. But it's less efficient (controls have a lot of overhead compared to eval expressions) and IMHO for something a heck of a lot less maintainable for such a simple thing.
# Code Blocks vs. Controls Collection - ASP - Coding & Web - Whirlpool Broadband Forums
by Whirlpool.net.au February 11, 2007 @ 6:13pm
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Stosh March 27, 2007 @ 6:37am
On my page, I was able to fix an instance of this error by moving script out of the <head> tag and into the <form> tag.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Alexander April 02, 2007 @ 4:04am
you can just move the script out of the head block to the form block. that works fine.
# ASP.NET Forums - Code blocks usage
by Web Forms April 16, 2007 @ 11:58am
# asp:image question - ASP.NET Forums
by ASP.NET Forums May 28, 2007 @ 11:57pm
# Code blocks usage - ASP.NET Forums
by ASP.NET Forums June 03, 2007 @ 8:42am
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by almir June 11, 2007 @ 5:14pm
it worked,
I love you
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Sam August 22, 2007 @ 1:47pm
Moving the script with the embedded <% %> tags from the head to the form tag worked for me too. Great article - thanks.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Mandy September 05, 2007 @ 1:03am
Thanks Rick, this was really helpful!
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Travich October 05, 2007 @ 9:49am
This happens when I add the ajax calenderExtender to my DataGrid. Funny thing is, that I didn't add any script... Now I can't figure out why this is happening. Grrr...


<asp:ImageButton runat="Server" ID="calImage" ImageUrl="/images/Calendar.gif" AlternateText="Click to show calendar" /><br />
<ajaxToolkit:CalendarExtender ID="calendarButtonExtender" runat="server" TargetControlID="txtTestedDate"
PopupButtonID="calImage" />
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Michael KOcher October 12, 2007 @ 7:21am
Thanks a bunch!
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Nitin Gupta October 24, 2007 @ 8:41am
That saved me a lot of time and frustration.........

Thanks!
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Wil October 30, 2007 @ 9:58am
Moving the script with the embedded <% %> tags from the head to the form tag worked for me too.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Josh November 01, 2007 @ 12:57pm
Worked perfectly, thanks for the heads up about this. You da man!
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Michael Clark November 07, 2007 @ 1:46am
I've just had the same issue, requiring a bit of javascript inside a control to know the id of a control... my solution was in JS to add:-

var moo = "<asp:Literal runat="server" id="litMonkey"></asp:Literal>";


then in the code-behind...

litMonkey.Text = objMonkey.ClientID
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Timmus December 06, 2007 @ 10:03pm
Thank you, sir. I am using multiple AJAX ModalPopupExtender controls and the user controls depend on the pageLoad event. I moved all the usercontrol javascript code to the host page to support a number of controls (this is a CRM app). Unfortunately I encountered the above mentioned error. I almost cried :). Thank you for posting your findings as it has been very helpful.

Timmus
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Ganesh December 13, 2007 @ 12:11am
Great!!!It worked out and no erros received....Thanks for sharing
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Alex February 20, 2008 @ 6:47am
Wow. Thanks for sharing.
Your blog is a gem!!! Keep up :)
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Dan February 26, 2008 @ 6:33pm
I had a similar problem to the GridView comment above, but it happened when I added the AJAX Calendar Control Extender to a Repeater control.

The problem went away once I removed the <%# %> from the javascript in the header. I would not call this a 'fix' though. I was able to work around the absence of the code block in the script this time, but may not be able to in the future.

I have also managed to add some key script code dynamically in server-side code (for instance, creating variables and all the script, but add assignments to those variables server-side)

Good blog!
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Dan Sharpe February 28, 2008 @ 12:24pm
I found two more reasons this error can occur while upgrading to VS 2008 Ajax using the AjaxControlToolKit for .net 2.0 and 3.5

When the MaskedEditExtender/CalendarExtender is used, a <LINK ...> tag to a stylesheet will result in this error. One workaround is to move the CSS file to a theme folder and add a reference to the theme in the web.config file <pages theme="themeName">. Each page needs to have the "<head>" tag replaced with "<head runat="server"> and any "<LINK ...>" tags removed.

Also, comments in the HEAD section can cause this problem. Take the following javascript example:

function DelLot()
{ // Called to delete the order.
// true means it was deleted -- false means it was not.
// return(window.showModalDialog("AskDelete.aspx?MODE=D&EBID=<%=nID%>", null,"dialogwidth:600px;dialogHeight:400px;help:no;resizable:no;scroll:no;status:no"));
}

Temporarily commenting out this javascript code, or perhaps anything in the head section, will still result in the same error when the page init event is fired. If the code block is needed, the javascript can be moved from the head section to the body section. Otherwise, you need to remove the code block completely, because commenting it out is not enough to resolve this error.

Good luck, Best, db.netDan
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Rima March 10, 2008 @ 11:09pm
Thanks Dan,

Your comment has resolved my problem. I also had a code which was commented. i have removed it and problem is solved.

Thanks again.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by jay May 28, 2008 @ 10:36am
Thanks Rick !!!!

I solved the problem by placing a PlaceHolder and moving the script block from head to form tag...

You saved my day!!!!
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Mike June 04, 2008 @ 11:56am
Neither of the methods described in the article above work for me. There must be some cases where this still is a problem. I have tried:

1) Switching to <%# ... %> tags, I just get no output from these at all, no good.
2) Wrapping <script> block in a <div runat="server"> block, no effect.
3) My script is already in the <FORM> tag, so nothing I can try there.

My code is in a user control, not sure if that has anything to do with it or not. NONE of the solutions presented on the web that others are claiming are working are working for me. This pisses me off.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Rick Strahl June 04, 2008 @ 1:27pm
<%# %> tags require databinding. You'll need to bind in order for that to work.

Wrapping in a <div runat="server"> or a asp:PlaceHolder control should always work to ensure that <%= %> tags are isolated from the parent container. The key is to have an independent container that contains nothing else.

<script> is not affected at all by any of these - this only concerns <% %> tags.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Jeremy June 10, 2008 @ 10:10am
Oh you rock! I was losing hope as at first the solutions weren't working. Then I read that last blurb about the server div and it finally clicked, and worked! Woo hoo! Thanks for this!
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Prashanth August 06, 2008 @ 11:57am
Hey guys this blog helped me a lot u guys rocks...
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Aaron August 13, 2008 @ 10:31am
I also moved the script out of the head to the body and it worked.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by sohan kanojia August 20, 2008 @ 10:01pm
gud work it's really work thanks a ton.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Larry Pauley September 12, 2008 @ 6:34am
I dont know if anyone else found this, but if you specify your script in the following manner, the problem will go away. Make sure you include the begin and end HTML commented out lines.

<script type='text/javascript'>
<!--
(javacript goes here)
//-->
</script>
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Rick Strahl September 15, 2008 @ 2:05am
@Larry - I don't think that makes a difference. It's the <%= %> tags that cause the problem when embedded in the script block. Haven't tried it but I'm pretty sure that it would still fail because we're talking about server side tags here.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Theone84 September 27, 2008 @ 5:23am
Yes it Worked Alexander ,Thanks
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Patrick Farrell October 01, 2008 @ 7:26pm
Thanks Rick. I just ran into same thing. Betcha it's my Java background.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by TurtleWax October 21, 2008 @ 10:26am
Rick, the "div/runat=server" trick seriously saved me. Thanks...
Your post is now 2 years old, so assuming your opinions hasn't changed, what were your concerns about this approach?


<div runat="server">
<script type="text/javascript">
function ShowCreditCard()
{
}
</script>
</div>
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Issa Qandil October 23, 2008 @ 7:48am
This is really helpful thanks guys ;)
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Lisa October 23, 2008 @ 11:00am
Thanks for posting this! You saved my bacon.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Vladimir October 30, 2008 @ 1:40pm
Hi Rick,

Just run into the same ugly problem. My workaround is to use ClientScriptManager (or in my case its AJAX'ed version, ScriptManager class, from Page_PreRender (where we have a correct ClientID):

if (!sm.IsInAsyncPostBack)
{
ScriptManager.RegisterClientScriptBlock (upDummy, upDummy.GetType (), "startup", string.Format ("var favNameClientId='{0}';", edFavName.ClientID), true);
}

This way it will embed in resulting HTML the script statement:
<script type="text/javascript">
//<![CDATA[
var favNameClientId='edFavName';//]]>
</script>

Note that this statement will be inserted at the very beginning of <body>, actually right after <script src="..."></script> blocks, so it safely can be used whenever below this point from javascripts at this page.

Also note, that this value will remain unchanged while async postbacks, so you don't need to call this method during later async postbacks, but only that's why it's wrapped in 'if'

Cheers,
Vladimir
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Chris October 30, 2008 @ 2:04pm
I've tried a lot of these suggestions and nothing seems to work. I am using the <% %> tags to get resource variables for internationalization of an application. One of the tags is being passed into a javascript function on a postback. I've tried using the #, instead of =, but then the link disappears. I've also attempted to move the javascript into the body of the page, but that doesn't work either. I am using Master pages. Any help would be greatly appreciated. Thank you.

Chris
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Fortune Ngwenya November 17, 2008 @ 10:41pm
you're the man!
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Atef Elkabani November 19, 2008 @ 5:48am
I have faced the same problem.

that because you can't add control

"Me.Master.FindControl("form1").Controls.Add(ctrl)"

to a form that have block (<% ... %>)

The best solution is to remove that block and try other solution
like add server side control

e.g

<a runat="server" id="lnkHome">

lnkHome.href= session("linkTitle") 'vb Code

instead of

<a href="index.aspx"><%= session("linkTitle") %> </a>
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Nicolas November 25, 2008 @ 6:22am
Thank you people!!!

<div runat="server">
<script type="text/javascript" language="javascript">
...
</script>
</div>


works like a charm!!
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Mike December 07, 2008 @ 11:30am
Yes, thank you!

I wish I had come across this page two years ago!
# The Controls collection cannot be modified because the control contain
by DotNetKicks.com December 18, 2008 @ 11:23am
You've been kicked (a good thing) - Trackback from DotNetKicks.com
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by proxy December 23, 2008 @ 6:05am
<div runat="server">...saved my ass!!

Thanks,
:)
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Sudheer January 05, 2009 @ 5:36am
Thank you ... :)
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by me January 13, 2009 @ 11:31am
thanks, using the <div runat=server... then a script tag helped me... really doesn't seem so intuitive... thanks!
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by DD February 03, 2009 @ 8:39pm
Hey there! I seriously need help with this one. I am trying to use the Calendar Tool and came across the said error.

I tried the <%#> <%> solution but it didn't work for me (or maybe I'm doing it wrong).

My MasterPage does not have any <%><%> code but the content page does have a couple.

Here's a snippet from the content page.
<%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="page.aspx.vb" Inherits="Dashboards_page" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>

Any ideas? Thanks in advance.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Roch March 01, 2009 @ 3:23pm
<div runat=server> Didnt help me.

But, I moved my JS code from <head> to the end of the <body>, and it worked fine!
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Rick Strahl March 01, 2009 @ 3:39pm
@Roch - a Div tag in the header is not legal, so that's why that probably didn't work. That or because your head tag didn't have a runat="server" in it. The trick is simply to get a server control to wrap script to force the container into its own logical generated code unit.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Faredoon March 02, 2009 @ 10:57pm
The <div> solution: superb.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Raja March 28, 2009 @ 4:52am
The DIV tag solution is working fine.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Robert Werner April 24, 2009 @ 5:34pm
Rick, your piece and that of several others eventually helped me find a solution.

After a lot of research, I've found a programmatic and non-programmatic way to accomplish this. You can read it here: http://mwtech.blogspot.com/2009/04/2-ways-to-load-jquery-from-aspnet.html

I hope it helps out your many readers!
# The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %> ).
by Rupendra Dhillon's ASP .Net Blog June 26, 2009 @ 2:40am
I am pretty sure that any web developer would hate an exception that is hard to catch. One of those is
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Nuno Santos June 27, 2009 @ 2:06am
First of all sorry my "bad" English.
I try to have a asp:datalist with a calendar extender on edit template, but every time I run the code and put the asp:datalist in edit mode I get the same error (The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)).
thks
NS
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Ahmed Assem August 04, 2009 @ 4:00pm
You can try removing the runat="server" from the head tag. this worked for me
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by choukei August 05, 2009 @ 11:16pm
The same error was displayed.

and after a long time's work .

i only put the js out of the <head></head>,but between <head> and <body>.

it is works well.

My english is a little bad.

hoho~~
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by rashmi August 14, 2009 @ 9:14am
Nice article was able to find the root cause and fixed it using
http://www.aspnetresources.com/blog/code_blocks_inside_master_pages_cause_trouble.aspx

Thanks for the details and everyone's input
# How to fix this .. The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Abdulla AbdelHaq Blog September 16, 2009 @ 8:32am
Sometimes when you write inline code inside Javascript tag or inside style sheet tag within the header
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by karthick October 04, 2009 @ 4:25am
i too have solved this problem by removing script section from head tag to inside the body tag
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by bob October 30, 2009 @ 1:07am
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by venkat November 10, 2009 @ 10:02pm
div runat=server is working great, thank u very much for ur comments guys
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Jake December 08, 2009 @ 11:32am
Rick Strahl! Thanks again for the great tip!

I used WWWC for WFP from 2002-2005 and reminisce pretty fondly over it. We were using it to make AJAX-style callbacks from Flash...
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by jon January 08, 2010 @ 10:12am
THANK YOU!!!!! The Data bindinng # worked !!!
THANKS FOR PUTTING THIS ON A BLOG!!!!!!
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Om Shanker Mishra February 06, 2010 @ 5:04am
Thanks a lot! Its really what I needed.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Akshaya March 31, 2010 @ 11:16pm
thank u so much... i have been struggling on this from past 15 days... its resolved today.
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Doug Den Hoed April 02, 2010 @ 11:27pm
Splendid! Thank you Rick. I had to read it a couple of times, but found your solution right away and used it to fix my project in less than an hour.

For future victims, what caused the error in my case was adding a Theme for the first time to my VS2008 C# project. Replacing each <% %> with <# %> in my Default.Master got me past the error and showed some of the Theme...but it was ugly. In the end, I went back to <% %> everwhere, and simply added a <div runat=server> around each of my three asp:contentplaceholder controls since each "helpfully" comes with a generated description of each in front that is wrapped with...you guessed it...<% %> symbols to mark them as comments.

Regards,
Doug
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by james May 06, 2010 @ 6:13pm
thanks heaps man :)
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Kishore Kumar Nethala May 18, 2010 @ 9:38pm
Move the javascript <script> tag to the bottom of the page It Works !!..
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Vin June 22, 2010 @ 11:47am
Just replace <%= by <%# and it will work
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by ITalez June 23, 2010 @ 1:04am
I can confirm that moving the javascript with <% %> tags from the head to the form tag fixes this error

http://italez.wordpress.com
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Elton Tadeu July 13, 2010 @ 4:10pm
Valeu brother...
comigo funcionou usando o <div runat="server"><%= ... %></div>
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Manaf August 03, 2010 @ 10:46pm
Thanks a million people , i thought it will never work ,
the Div runat Server worked like a charm , thanks God

<div runat="server">
<script type="text/javascript">
....
<% =CSharpFunction() %>
</script>
</div>

Manaf
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by KiS November 10, 2010 @ 10:29pm
Hi, thanks for the tip guys.

Yes, moving the javascript with <% %> tags from the head into the form tag works for me as well!

Cheers!
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Syed Shomaail Jafri December 04, 2010 @ 3:37am
gr8 work
thanks
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Anup Dharia January 13, 2011 @ 11:31pm
Thanks a million people , i also thought it will never work ,
the Div runat Server really worked like a charm.

<div runat="server">
<script type="text/javascript">
....
<% =CSharpFunction() %>
</script>
</div>
# re: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
by Dyamanagowda June 24, 2011 @ 6:40am
Thanks a Lot Rick . I removed my code from head block and put all my scripts inside th body under div tag as u mentioned. Its working fine.


Regards,
Dyamanagowda
 


West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2014