Question

I'm working on a web form site. The head tag has the runat server attr. in the master page.

I'm trying to use ResolveClientUrl for a .js file like this:

 <head runat="server">
   .. 
  <script src='<%= ResolveClientUrl("~/myscript.js") %>' type="text/javascript" >    </script>
 </head>

But then, I got an error:

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

I found out that the problem was the runat server, so I removed it from the head tag... and now I'm getting the following error:

Using themed css files requires a header control on the page. (e.g. <head runat="server" />). 

So, how can I use the ResolveClientUrl inside a runat server head?

UPDATE:

I've added the script using an include at the master page's top (seems to work fine).. but there might be a better solution.

<!-- #include file="myscript.js" -->
Was it helpful?

Solution

You can use databinding:

<head ID="head" runat="server">
    ..
    <script src='<%# ResolveClientUrl("~/myscript.js") %>' type="text/javascript" >    </script>
</head>

Then in your code-behind (preferably in the Page Load event handler):

head.DataBind()

OTHER TIPS

The reason you get that message is because when code blocks are introduced, the ControlCollection for the containing runat="server" control must be locked to prevent an unexpected condition that the core framework wouldn't be able to recover from when rendering (and therefore executing the render code blocks)

And complicating things is when using any code that wants to "add itself" into the server control collection.

To prevent this, the best way is to wrap any code blocks in a Literal control in the head:

<head runat="server">
   <title></title>
   <asp:Literal runat="server" id="SCRIPTLIT1">
    <script src='<%# ResolveClientUrl("~/myscript.js") %>' type="text/javascript"></script>
   </asp:Literal>

<!-- ...other stuff -->
   <asp:ContentPlaceholder runat="server" id="head"></asp:ContentPlaceholder>
</head>

So now we've pushed the framework into locking the control collection of the Literal and not the <head runat="server"> control collection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top