0

Sometime we need to put / or ~/ as the suffix in order to make refer to the root

<script type="text/javascript" src="/scripts/jquery-1.5.1.min.js"></script>
<link href="~/Styles/MasterPage.css" rel="stylesheet" type="text/css" />

This is what i know from Phill

~/ is not valid unless you have a runat attribute on your control/element. '/' by itself specifies to the browser to look from the root directory, so if you link to '/css/main.css' from www.mysite.com/product/view.aspx it will look for the css file in www.mysite.com/css/main.css. When you use '~/' with runat-server, it will work out the path to the directory at runtime, so in the same example with '~/css/main.css' the rendered url will look like '../css/main.css' because it needs to drop the directory back 1 before finding the directory 'css'. (hope that makes sense) – Phill How to include jquery in masterpage header without path problems?

but as i has tried, even i use / firefox still refer to ../../ instead of static path. also, I don't know it clearly how to use it correctly , which one use on which situation.

Community
  • 1
  • 1
Sarawut Positwinyu
  • 4,974
  • 15
  • 54
  • 80

2 Answers2

3

~/ refers to virtual directory application root where as "/" refers to site roots eg if you have site that in http://www.example.com/ and which has http://www.example.com/foo where folder "foo" configured as virtual directory application in IIS a page in http://www.example.com/foo/foo.aspx will resolve ~/ as relative to virtual directory application root directory which is http://www.example.com/foo but "/" will still resolve to site root which is http://www.example.com/

DSharper
  • 3,177
  • 9
  • 29
  • 47
3

The / at the beginning of a relative URL backs up to the root of the hostname.

The prefix ~/ in a relative URL can only be interpreted by the ASP.NET process, which is why it only works for runat=server. It is translated upon output to refer to the root URL of the ASP.NET application. Many times, this is the same as the root of the hostname, but it will differ if the ASP.NET application that the code is running in is a virtual directory in IIS rather than its own site.

If you only need to drop one directory level back, you can use "../" as the prefix rather than "/" or "~/".

richardtallent
  • 34,724
  • 14
  • 83
  • 123