Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS and Javascript relative path confusion in ASP.NET MVC

Tags:

My javascript paths work on this page: http://localhost:53049/

But not on this page: http://localhost:53049/Home/Messages

The reason is that the relative paths are different, the former requires ("js/...") and the latter requires ("../../js/...").

I'm including my javascript in my Site.Master file:

<script type="text/javascript" src="js/jquery.jqGrid.js"></script> <script type="text/javascript" src="~/js/jquery.jqGrid.js"></script> <script type="text/javascript" src="<%= this.ResolveClientUrl("~/Scripts/jquery-1.2.6.js") %>"></script> 

How do I get around this relative path madness, i.e. what is the best practice way in ASP.NET MVC to set CSS/Javascript paths in the Site.Master so that they work for each view no matter how deep that view's URL happens to be.

ADDENDUM:

It seems that for the Index view, any path will work, strangely:

<script type="text/javascript" src="/Scripts/jquery-1.2.6.js"></script> <script type="text/javascript" src="../../Scripts/jquery-1.2.6.js"></script> <script type="text/javascript" src="../../../Scripts/jquery-1.2.6.js"></script> 

But for any other pages (pages with a deeper URL), none of these work.

What's going on here? How can we set the Javascript path once in Site.Master and they work for all pages?

ADDENUM II:

It turned out to only be a problem with the jqgrid javascript file (not the jquery file), apparently inside that file it is referencing other javascript files and gets confused:

<script type="text/javascript" src="<%= Url.Content ("~/js/jquery.jqGrid.js") %>"></script> 
like image 715
Edward Tanguay Avatar asked Jan 12 '09 15:01

Edward Tanguay


2 Answers

You can also use the Url.Content method call to make sure that the paths are correctly set.

Examples can be found here.

like image 174
Kieron Avatar answered Sep 20 '22 04:09

Kieron


Regarding paths used in CSS documents:

/Content/site.css

Body {background-image:url('background.jpg');} 

Relative paths in CSS documents are related to the CSS document, not the document being displayed.

This information saved me some headaches.

like image 34
Ropstah Avatar answered Sep 22 '22 04:09

Ropstah