6

I've read many articles about relative/absolute paths, but I still can't grok this problem.

The following code is from my ASP.NET Master page:

<li><a>Reports</a>
    <ul>
        <li>
            <a href="/Reports/One.aspx">One</a>
        </li>
        <li>
            <a href="~/Reports/Two.aspx">Two</a>
        </li>
    </ul>
</li>

(Note that one link has a ~ and one doesn't.)

When running the site, the first link points to http://server/Reports/One.aspx, and the second link points to http://server/company/project/Reports/~/Reports/Two.aspx.

How do I get to the root of my ASP.NET project without it ignoring whatever virtual directories are set up on IIS?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
notAnonymousAnymore
  • 2,637
  • 9
  • 49
  • 74

4 Answers4

15

Add runat="server" attribute to the anchor tag. You can't use the ~ root operator with HTML tags. Only the server controls (Html or Web) can use it.

<a runat="server" href="~/Reports/Two.aspx">Two</a>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • works like a charm!, thank you!, but why that it made the trick? – dennisbot Apr 29 '13 at 03:02
  • 1
    @dennisbot - `runat="server"` causes IIS to preprocess the tag. The ASP symbol ~ is resolved to the root of the web app and an absolute URL is delivered to the browser. – Peter Wone Aug 19 '16 at 00:27
12

Use Page.ResovleUrl for all of your files if you don't want them to be server controls with generated Ids:

<a href='<%= Page.ResolveUrl("~/Reports/Two.aspx")%>'>Two</a>
rick schott
  • 21,012
  • 5
  • 52
  • 81
6

A relative path is relative to the current resource, so if you were viewing

http://yourhost/app/default.aspx

a relative path of reports/one.aspx would be http://yourhost/app/reports/one.aspx. Note the absence of a leading / in the relative path. That's what makes it relative.

An absolute path, as you can probably guess, starts with a /, and it uses the hostname of the current resource, so that would http://yourhost/reports/one.aspx.

~ is an red herring. It's a .NET-only addition used by various parts of ASP.NET to base your path off the current application root. So if your application root was http://yourhost/app, you were viewing http://yourhost/app/views/default.aspx, and you asked .NET for the path ~/reports/one.aspx', you would be givenhttp://yourhost/app/reports/one.aspx`.

~ isn't used by HTML, IIS or URLs, so if your browser sees it, it'll just use it as is.

Note: Some Unix servers can use ~ to map in a user's home directory, but that's just complicating things.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Simon Halsey
  • 5,459
  • 1
  • 21
  • 32
1

Please read There is something about "Paths" for ASP.NET beginners. It will give a complete idea on "Paths" in an ASP.NET application.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
himanshu
  • 434
  • 3
  • 8