04 March 2008

How to resolve JavaScript and CSS files path in master pages

JavaScript and css files path in master pages is a problem if the aspx pages are not in the same structure. For example, you may want some page on the site root (like default.aspx, login.aspx and logout.aspx) and others on a folder to organize the site.


The first attempt to solve this problem is use code blocks (<%= ... %>) with ResolveUrl, which give the following error:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).

The second attempt is to use  <%# ... %>) and ResolveUrl, but nothing is returned to the browser.


The third attempt is to data bind the HtmlHead in code behind of the master page, since it derives from Control:

protected override void OnLoad(EventArgs e)

In the master page write: 

<style type="text/css"> 
  @import '<%# ResolveUrl("~/shared/css/style.css") %>'; 
  @import '<%# ResolveUrl("~/shared/css/grid.css") %>'; 
<script type='text/javascript' src='<%# ResolveUrl ("~/shared/js/library.js") %>'></script>

The css problem can also be resolved with:

<head runat="server"> 
<link href="shared/css/style.css" rel="stylesheet" type="text/css" /> 

The path is relative to the master page, and Asp.Net will solve the path based on the master page location.

The JavaScript files are still the problem. The third solution will fix it, or some code behind is in order!!!

A more elaborate solution would be to use resources and the WebResource.axd handler....

1 comment:

Rod Lowe said...

Hi -

Try adding this to the code behind (VB):

Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
Page.ClientScript.RegisterClientScriptInclude("meiMain", ResolveUrl("includes/mei08Main.js"))
Page.ClientScript.RegisterClientScriptInclude("p7Acc", ResolveUrl("p7ap/p7APscripts.js"))
End Sub