October 09, 2008

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

1 of 1

Who?

Howdy. I'm Richard W. Baker - a designer based in Jacksonville, Florida with a passion for information architecture and usable interfaces. At my day job, I work for the City of Jacksonville as a User Interface Designer.

If you still have questions, or you're interested in hiring me for your next project, .

Active ingredients: XHTML + CSS + Expression Engine
Page rendered in 0.2033 seconds  |  50 SQL queries total