Lions Den

The Code and Times of Hanan Schwartzberg

About Hanan | Hanan's CV | Contact Hanan

November 18, 2013

ASP.NET Relative Urls (~/) Not Rendering Correctly in a HyperLink ImageUrl

Filed under: ASP.NET,C# — Tags: , , , , , , , , , — Hanan Schwartzberg @ 2:47 pm

The Issue

When using a HyperLink object on masterpage the relative url assigned to the ImageUrl property is not resolving correctly on certain pages. The problem appears to only affect pages where a url rewrite has been used and the level of directories does not match the actual level of directories of the page. For instance, if the url “” actually loads “”, the the below hyperlink will resolve as “../products/images/bbb_logo.gif”. On all other pages it will correctly resolve as “../images/bbb_logo.gif”.

<asp:HyperLink runat="server" ID="hlBBB" Target="_blank" 
        NavigateUrl="" ImageUrl="~/Images/bbb_logo.gif" />

Attempting to resolve the url manually in the code behind doesn’t work either. The following code results in the same incorrect url.

hlBBB.ImageUrl = ResolveClientUrl("~/images/bbb_logo.gif");

The Solution

There are two ways to work around this.

  1. This bug seems to be exclusive to the HyperLink object. Remove the image from the HyperLink and the ImageUrl will resolve correctly. For instance, the above HyperLink should be rewritten as:
    <asp:HyperLink runat="server" ID="hlBBB"
        <asp:Image runat="server" ID="imgBBB" ImageUrl="~/Images/bbb_logo.gif" />
  2. If you really want to leave the image in the HyperLing object. You can work around the problem in the code behind. The ResolveClientUrl method doesn’t work because takes into account the page’s location in the site, which between the rewrite and the actual location of the page seems to be inaccurate. Instead use VirtualPathUtility.ToAbsolute to resolve the url. This method can be used anywhere on the site, not just on pages and user controls and will resolve the url with an absolute path (“/images/bbb_logo.gif”).
Home | Site Design | Banner Design | Code Den | Offsite Posts | Downloads | Photography | About Hanan | Hanan's CV | Contact Hanan
Copyright © 2009 Hanan Schwartzberg. All rights reserved.