(Microsoft .NET,Microsoft ASP.NET)
by Jason Skowronek
on 04/07/2011
Over the years, I have run into this issue multiple times and have decided to document my top two solutions. There are plenty more out there, these are mine.
Problem
You attempt to run ASP.NET code blocks (<%= %>), such as trying to resolve the application root using
<script href="<%= ResolveUrl("~/Js/Default.js") %>" />and have the <head /> tag of your Master Page or Web Form set to runat="server" you will get the following runtime error:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)
Solutions
Here are (in my opinions) the cleanest solutions I have found with the least impact on code behind and time to implement.
Solution One
Wrap your code blocks in a server control. I use a plain-ole PlaceHolder control.
<asp:PlaceHolder runat="server">
<script src="<%= ResolveUrl("~/Js/jquery.js") %>" type="text/javascript"></script>
</asp:PlaceHolder>This prevents the error but also does not render an actual control. All good.
Solution Two
Use a databinding tag <%# %>
<script src="<%# ResolveUrl("~/Js/jquery.js") %>" type="text/javascript"></script>The only caveat to this is that you need to fire the DataBind event for the head control onLoad or onInit.
Page.Header.DataBind();
Of the two solutions, I find option one my preferred as it requires less (no) back-end code.
Related Articles