views:

45

answers:

2

When i drag and drop my image/script/css file into my view, relative path will automatically use to refer on the files.

example:

<link href="../../Content/style.css" rel="stylesheet" type="text/css" />
 <script src="../../Scripts/jquery-min.js" type="text/javascript"></script>
 <img src="../../Images/logo.jpg" />

It is working fine when i host it on my root directory, but if i'm using virtual directory then only my css file able to refer correctly, the rest will return 404...as it will refer to http://{root}/Images/logo.jpg rather than http://{root}/{virtual directory}/Images/logo.jpg

But why css file is working? and how to specify the relative path correctly for both root & virtual directory cases?

+4  A: 

something like...

   <script type="text/javascript"  
            src="<%= Url.Content ("~/Scripts/jquery.js") %>">
   </script> 

will do the trick

Keith Nicholas
+1  A: 

Also, related to Kazi Manzur's MVC Best Practices, you could create UrlHelper methods to handle the creation of all of your content (script, stylesheet, images, etc) filepaths. That way, if you change the directory, all you have to do is change the corresponding UrlHelper:

   public static string Style(this UrlHelper url, string fileName)
   {
       return url.Content("~/content/{0}".FormatWith(fileName));
   }

   public static string Script(this UrlHelper url, string fileName)
   {
       return url.Content("~/scripts/{0}".FormatWith(fileName));
   }

Then, in your ViewPage or MasterPage, you can write the paths like so:

<link  href="<%= Url.Style("site.css")%>" rel="stylesheet" type="text/css"/>
ewwwyn
Interesting. I guess this is used to handles situations when production doesnt match up to devevelopment or test configurations. Seems that reading these out of web config would make it even more dynamic.
MikeJ
Thanks, but with this method i will lose my javascript intelliSense in Visual Studio. What i do now is to add a custom httpmodule, before the page is return back to client, it replace "../../" with absolute path inside the html.
kevin