Code Blocks Inside Master Pages

Some time ago I kept getting this error in one of the projects I was working on:

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

I spent quite some time trying to figure it out. Finally after hours of searching I found out that Code Blocks Inside Master Pages Cause Trouble.

I was using code blocks inside the head tag of all the MasterPages to resolve paths at runtime:

<link rel="stylesheet" href="<%= ResolveUrl("~/myStyleSheet.css") %>" type="text/css" />
<script type="text/javascript" src="<%= ResolveUrl("~/myJavaScript.js") %>"></script>

Fortunately Milan Negovan proposed a quick workaround which saved a lot of time.

Basically, the workaround is to change the code blocks to data binding expressions (<%# … %>).

<link rel="stylesheet" href="<%# ResolveUrl("~/myStyleSheet.css") %>" type="text/css" />
<script type="text/javascript" src="<%# ResolveUrl("~/myJavaScript.js") %>"></script>

and adding this to the master page code behind:

protected override void OnLoad (EventArgs e)
{
  base.OnLoad (e);
  Page.Header.DataBind ();
}

Since HtmlHead ultimately derives from Control and everything that derives from Control has a DataBind() method, adding that one line above would force the header to resolve data binding expressions.

Thats it, that does the trick!

If you liked this post, 🗞 subscribe to my newsletter and follow me on 𝕏!