use of tilde (~) in asp.net path
C#asp.netC# Problem Overview
i'm working on an asp.net app, the following link works in IE but not in FF.
<a href="~/BusinessOrderInfo/page.aspx" >
Isn't the tilde something that can only be used in asp.net server controls. Where it will be replaced by an actual path?
Is it possible to use the tilde in an anchor tag? If so what does it mean?
When I'm at the root, the link works
www.myserver.com/default.aspx, click the link, ok!
www.myserver.com/otherpart/default.aspx, click the link, not ok!
The link generated by ASP.NET is:
www.myserver.com/otherpart/~BusinessOrderInfo/page.aspx
Is this by design?
C# Solutions
Solution 1 - C#
You are correct, it only works in server controls. You've got these basic options:
Change to HyperLink
to run as a Web Control:
<asp:HyperLink NavigateUrl="~/BusinessOrderInfo/page.aspx" Text="Whatever" runat="server" />
Or, run the anchor on the server side as an HTML Control:
<a href="~/BusinessOrderInfo/page.aspx" runat="server" >
Or, use Page.ResolveUrl
:
<a href="<%= Page.ResolveUrl("~/BusinessOrderInfo/page.aspx") %>">...</a>
Solution 2 - C#
HTML controls can be turned into server controls by adding the runat="server" attribute.
<a href="~/BusinessOrderInfo/page.aspx" runat="server">
Solution 3 - C#
The tilde refers to the application root directory, and will be translated correctly in control properties such as NavigateUrl.
My understanding is that if you use it in plain-HTML tags, it will not be translated by ASP.Net.
Solution 4 - C#
If you remove tilde and use forward slash only you will achieve the same result, i.e. pointing to the root folder on the current domain:
<a href="/BusinessOrderInfo/page.aspx" >
Solution 5 - C#
This function can also be used to resolve paths for non server elements
VirtualPathUtility.ToAbsolute($"~/App_Themes/Default/Icons/myimage.gif")