21

I'm confused with ASP.NET relative path, please can someone help?

In a Master Page I gave a link label referencing:

<a href="~/Account/Login.aspx">Login</a>

From the ASP.NET official documentation I read:

The following example shows the ~ operator used to specify a root-relative path for an image when using the Image server control In this example, the image file is read from the Images folder that is located directly under the root of the Web application, regardless of where in the Web site the page is located.

<asp:image runat="server" id="Image1" ImageUrl="~/Images/SampleImage.jpg" />

With the Login markup, when I click the link from a page in the /Account folder, I'm redirected to:

/Account/~/Account/Login.aspx

Why? WHY?h

Didier Levy
  • 3,393
  • 9
  • 35
  • 57

3 Answers3

35

Because you're using it directly in markup, rather than in a server control. Something as simple as this should fix it:

<a runat="server" href="~/Account/Login.aspx">Login</a>

Basically, the ~ path reference needs to be translated on the server, since it's a reference to the server path of the application's base directory. Plain HTML markup isn't processed on the server, it's just delivered as-is to the client. Only server-processed code will translate the ~ path to what it resolves to.

David
  • 208,112
  • 36
  • 198
  • 279
  • @MuhammadAli: Please use the "Ask Question" button on this page to ask a new question on Stack Overflow. Be sure to provide any relevant information about the problem in the question. Comment threads on a different existing question are not a good place to seek help from the community. – David Jul 01 '16 at 22:50