Tuesday, December 2, 2008

Making sure MasterPage CSS and JavaScript reference path are always correct

Depending on the folder, the relative path to CSS and JavaScript references may be different. We need toensure that regardless the path of the page that called the master page, the relative paths to the reference files are always correct. We also want the pages and master pages to display properly in Visual Studio and that the links are always relative.

Here is how to do it:

1. Make sure the head tag is runat=server
2. CSS should use a link tag with a relative path
3. JavaScript should use ResolveUrl built in Dot Net method to dynamically generate actual relative path

Here is the html source, assuming that the master page exists in ~/templates/ folder, the .js script exists in ~/scripts/ folder, the CSS stylesheets exists in ~/styles/ folder:

<head runat="server">
<title>Title of Page</title>
<!-- meta information goes here -->
<link href="../styles/layout.css" rel="stylesheet" type="text/css" />
<script type='text/javascript' src='<%= ResolveUrl("~/scripts/common.js") %>'>
</script>
</head>



2 comments:

AbC said...

Why must the path to the CSS file be relative? You can reuse the ResolveUrl function or use the tilde (~) character in the path along with a runat="server" attribute.

A IT Devotee said...

I found the best and simple solution it is just adding "ResolveUrl" while referencing the javascript file. link :
http://aspnetnova.blogspot.com/2009/05/masterpage-contentpage-javascript-path.html