You are not Logged in
Would you like to Login or Register

Today is: Friday, 21 November, 2008
Check this months hot topics

Programmatically resolving ~ URL's to the Virtual Root using ResolveURL()

It's common knowledge that a control, when Runat="server" will resolve it's src or href attribute to a virtual root when the URL starts with ~/

For example:

<a href="~/Customers/Profile.aspx" Runat="server">Profile</a>

will become:

<a href="http://yourdomain.com/site/Customers/Profile.aspx" Runat="server">Profile</a>

How do we do this programmatically?

The base WebControl class exposes a method named ResolveURL(). This method accepts a url such as "~/Customers/Profile.aspx" and returns the real url, starting from your site's virtual root.

To get to this functionality you can use the following pattern:

string url = Page.ResolveClientUrl("~/Customers/Profile.aspx");

..or..

string url = VirtualPathUtility.ToAbsolute("~/Customers/Profile.aspx");

..or..

Image x = new Image();
string url = x.ResolveUrl("~/Customers/Profile.aspx");
kick it on DotNetKicks.com del.icio.us digg Mister Wong YahooMyWeb Reddit Furl Spurl blogmarks
Paul Hayman Skype
Author : Paul Hayman
Published : Wednesday, 14 June, 2006

Paul is the COO of kwiboo ltd consultant and has more than a decade of IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services. Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.

Comments

Anonymous said:

Excellent article.... Really helped me out

July 12, 2006 - 3:33 PM

Vladek said:

Yes, it's very handy method.

Well, here is a method to resolve URLs for HTML tags, which are not or cannot be marked with runat="server":

<a href="<%= ResolveUrl("~/Customers/Profile.aspx") %>">Profile</a>

Just use <%=%> to place small pieces of code into HTML.

June 19, 2007 - 12:17 PM

said:

JIT information. :) Great work, and thanks!

October 11, 2007 - 5:16 PM

Me said:

It does not add the server, the output is more like

<a href="/site/Customers/Profile.aspx" Runat="server">Profile</a>

February 14, 2008 - 4:43 PM

Add Comment

Enter your comment below and it will be submitted for moderation.

Your Name

Add Tag

Please enter tags for this article, seperated by semi-colon ;

View Tag's by : # articles | # views

More Publications

Programmatically resolving ~ URL's to the Virtual Root using ResolveURL()
Paul Hayman - 14/6/2006
Referencing ConfigurationManager
Barrington Haynes - 14/6/2006
SQL Server 2005 mdf file Query String
Barrington Haynes - 14/6/2006
ASP.NET Framework 1.1 Validation not working in IE7?
Paul Hayman - 4/7/2007
TraceListener creates huge log files
Lee Keable - 26/7/2006