asp.netwebformsrunatserverresolveclienturl

ResolveClientUrl inside runat server head


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" -->

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()