Andornot Blog

Thursday, June 28, 2007 1:30 PM

ResolveUrl vs. ResolveClientUrl

by Peter Tyrrell

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.

blog comments powered by Disqus

Month List