Resolving relative URL’s from JavaScript

An entry about javascript | asp.net | asp.net mvc Publication date 22. August 2009 14:50

On the server side of an ASP.NET or ASP.NET MVC application, we’re used to working with relative URL’s in the style of “~/Images/logo.png”. This makes our application safely deployable to virtual directories within IIS applications without messing up the URL’s. However, what do we do if we need the same functionality in our JavaScript?

I’m solving this by sticking the following script in my Site.Master file:

Url = function() { }

Url.prototype =
{
    _relativeRoot: '<%= ResolveUrl("~/") %>',

    resolve: function(relative) {
        var resolved = relative;
        if (relative[0] == '~') resolved = this._relativeRoot + relative.substring(2);
        return resolved;
    }
}

$Url = new Url();

Now, anywhere I need to resolve a relative url in a script, I can do this:

var logoUrl = $Url.resolve("~/Images/logo.png");

Currently rated 4.6 by 5 people

  • Currently 4.6/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.

NDC 2010

The conference to attend this summer happens June 16th-18th in Oslo, Norway. Are you going? Be sure to catch my talk on AOP while you're there!

 

Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS