Thursday, January 15, 2009

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

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

So recently, I got the above error while trying to inject some dynamic tags into the head section of an ASP.NET 2.0 master page. Turns out that it's not possible to write a code like Header.Controls.Add(yourControl); if you are using code blocks to refer to stylesheets and js files and such -


<link href="<%= ResolveUrl("~/css/style.css") %>" rel="stylesheet" type="text/css" media="screen" />

<script type="text/javascript" src="<%= ResolveUrl("~/js/json.js") %>"></script>
. etc

So what gives? The most obvious solution is to of course get rid of code blocks but that's not always possible and might break some references if the user lands at some subfolders etc in your website.

Next solution is to use databinding....i.e., replace "<%=" with "<%#" in the code blocks. So the above css and js references become the following -


<link href="<%# ResolveUrl("~/css/style.css") %>" rel="stylesheet" type="text/css" media="screen" />

<script type="text/javascript" src="<%# ResolveUrl("~/js/json.js") %>"></script>
. etc

Since we are basically using the data binding expression "<%#" now for the head tag, you need to call the DataBind method after replacing "<%=" with "<%#" . That's just one extra line of code in your page load method -

protected void Page_Load(object sender, EventArgs e)
{
.....
.....
Head1.DataBind();
}

And, that's all there is! Problem solved!

No comments:

Post a Comment