Friday, May 30, 2008

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

This annoying error appeared out of nowhere in a project that used to work. I thought that the fault was of the new AjaxControlToolKit and the way it tries to register a CSS file. I was about to make really complex and , apparently, useless changes to my code until I've stumbled upon Rick Strahl's blog. It is not in the entry, but further down in the comments, but it's there.

Here is a distilled version: the error is not a page error, but a naming container control error. That means that if you do this in a PlaceHolder, let's say, it will only throw an error if the PlaceHolder has code blocks. The same applies to the header! The problem was not AjaxControlToolKit, but my own modifications to the MasterPage, where I had added script blocks with a dynamic URL.

So I added the script tags from the codebehind using this:

private void AddHeaderScript(string src)
HtmlGenericControl hgc=new HtmlGenericControl("script");
hgc.Attributes.Add("type", "text/javascript");
hgc.Attributes.Add("language", "JavaScript");
hgc.Attributes.Add("src", src);

. I don't know how this would work during an Ajax postback, but I wasn't interested in this, being a MasterPage thing. And it worked.

So, next time you get this error, be sure you know what control generated it. It can be solved by putting an extra PlaceHolder or, as is this case, replacing just some specific few code blocks.


Info @ said...

Lifesaver!!! Same error, same problem. Fantastico!