Andornot Consulting Inc.
Home Page
Home Page
 |  | 

Thursday, June 28, 2007

ResolveUrl vs. ResolveClientUrl

The .NET Control class methods ResolveUrl and ResolveClientUrl both take a relative URL as a parameter and return relative URLs for client browser use. So what's the difference between them?

In simple terms, ResolveClientUrl returns a path relative to the current page, and ResolveUrl returns a path relative to the site root. Both methods are particularly useful when passing in a relative URL prefaced with the tilde (~) to indicate the application root.

Let's say we have an image in a layout directory, and a page which needs to pass a usable relative URL for the image to the client browser.

image http://www.andornot.com/layout/images/andornotLogo.gif

page http://www.andornot.com/Products/Default.aspx.

Here is what we would get if we called the two methods from our Default.aspx page.

Page.ResolveUrl("~/layout/images/andornotLogo.gif")
"/layout/images/andornotLogo.gif"
Page.ResolveClientUrl("~/layout/images/andornotLogo.gif")
"../layout/images/andornotLogo.gif"
There is more to it, of course, particularly since these are Control methods, not exclusively Page methods. It's pretty straightforward to see how paths relative to a page resolve, but not necessarily so obvious when the control is being instantiated in a UserControl or MasterPage.

ResolveUrl uses the Control.TemplateSourceDirectory property to do its job, and that property value is the virtual directory of the Page or UserControl that contains the current server control.

ResolveClientUrl returns a URL relative to the folder containing the source file in which the control is instantiated.

Labels: ,

4 Comments:

Anonymous Joggee said...

So which one is preferable.
ResolveURL or ResolveClientURL Method.

Please recommend.

Joggee
http://blog.joggee.com

2:03 AM  
Anonymous Anonymous said...

Thanks for this post. It really cleared things up for me.

11:55 AM  
Anonymous Logan (logannet_net AT hotmail.com) said...

I would use ResolveUrl

The Url returned can be used anywhere in the site and it still work correctly

1:50 PM  
Blogger Kidde82 said...

Nice, thanks!

I got problems using ResolveClientUrl when using UrlRewriting, so I changed to ResolveUrl and it works just fine..

4:14 AM  

Post a Comment

<< Home