Reference JS file when using MasterPages

Problem

I need to reference a JS file in the <head> in a Master Page in Visual Studio 2008. In Visual Studio 2005, I did:


<script type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/jquery/jquery-1.2.6.min.js")%>"></script>

but this gives me an error:

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

I tried hunting down the error, and stumbled on Rick Strahl's post about a similar issue. Unfortunately, this didn't work for me.

Solution

Luckily some of my friends are better developers then I am. Turns out, the fix is to follow Rick Strahl's tip, but to databind() the head in the MasterPage's PageLoad()


<head id="html_head" runat="server">
	<title>City of Jacksonville</title>
	<script type="text/javascript" src="<%# Page.ResolveClientURL("~/javascript/jquery/jquery-1.2.6.min.js")%>"></script>
	<script type="text/javascript" src="<%# Page.ResolveClientURL("~/javascript/actions.js")%>"></script>
</head>

Then, in the MasterPage's code behind


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
	html_head.DataBind()
End Sub
Posted by on 10/09 at 06:56 AM

Name:

Email:

Location:

URL:

Smileys

Remember my personal information

Notify me of follow-up comments?

Submit the word you see below:


<< Back to main