Friday, August 10, 2012

The Controls collection cannot be modified because the control contains code blocks




The above error is very common when we try to access server side values on client side using Javascript.

The solution to this problem is simple.

1. The Server Tag to get values of any variable or property is as below
var propVal = '<%= ServerSideProperty %>';
This is also particulartly helpful when accessing Web.Config values in Javascript as:
var configVal = '<%= ConfigurationManager.AppSettings["ConfigPropName"] %>';

This would raise the above error. And the solution to it, "Replace the "=" with a "#""
So now your properties would be something like
var propVal = '<%= ServerSideProperty %>';
var configVal = '<%= ConfigurationManager.AppSettings["ConfigPropName"] %>';

Now, if you are accessing any Data bound values, such as in a grid view etc, then this would work good for you but for accessing properties or other variables, here is another small piece of code required.

On Page Load, we need to Bind these together using
Page.Header.DataBind();
Unless you do this, you would not be able to access these values and they would return a BLANK.