Marc LaFleur

Thoughts on finding a better way

Getting jQuery to work with MasterPages - Code Junkie

Jared Roberts asked a question today on his blog about using jQuery with ASP.NET Master Pages (Getting jQuery to work with MasterPages - Code Junkie). Master Pages present some interesting problems. Because the Content Page could live at a different directory level than the Master you can quickly run into issues with relative paths breaking.

The solution is to place your scripts references into a ScriptManager on the Master Page. This ScriptManager will render the proper <Script> tags for you at runtime. For example:

<asp:ScriptManager ID="ScriptManager" runat="server">
    <Scripts>
        <asp:ScriptReference Path="~/js/jquery-1.2.6.min.js" />
    </Scripts>
</asp:ScriptManager>

The downside of this is that your Content Pages will lack Intellisense for the scripts you’ve referenced. The workaround for this is to give the designer a reference it can use at design time but that won’t render at runtime. This is done by placing the following code into your Content Page:

<%
   if (false) { 
%>
    <script src="../js/jquery-1.2.6-vsdoc.js" type="text/javascript"></script>
<%

}

%>

This gives you properly pathed <Script> tags at runtime and JS Intellisense at design time. This also works with User Controls where you’re using a ScriptManagerProxy and want Intellisense support.

As an aside, the <% if (false) { %> trick is useful for other design time content. We’ve used it to reference style sheets when building user controls. It lets the control developer get a good visual of what the final control might look like but allows the final styles to be controlled by the page hosting the control.

Posted: Dec 24 2008, 11:27 PM by MarcLaFleur | with 2 comment(s) |
Filed under: , ,

Comments

rojay12 said:

Thanks!

# December 26, 2008 1:39 AM

Rachti said:

I blogged about this issue in my old blog here:

geekswithblogs.net/.../103608.aspx

Hope it helps!

# December 26, 2008 6:25 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)