The short version:
- Put a
<base>element with an
hrefattribute in the
<head>section of your MVC view (this could be your
_Layout.cshtml). Use ASP.NET MVC helpers to generate a value for the
hrefattribute reference path.
- Get the attribute value from your script.
For code example, see the bottom of this post or this gist.
A more detailed discussion follows.
Problem with MVC URLs and static content
I’ve found that I sometimes need to reference another resource from a script, e.g. when specifying view files for Angular.js routes. However, when using ASP.NET routing (or any routing where a URL refers to a resource, not necessarily files), resource URLs become problematic.
Relative URLs to a resource are often unusable, e.g. the same script may be used from
'/Home/Edit/1', etc. If this script would contain a relative reference, e.g.
'../img/myImage.png', it would work only for one depth.
A better option is using URLs that are relative to root, e.g.
'/img/myImage.png'. Now it would work for all aforementioned URLs. The problem with this approach is that the browser interprets it as relative to the domain root, e.g.
'http://www.example.com/img/myImage.png'. Often Web sites are hosted on subfolders of a domain, e.g.
'/app, so the correct URL in this case would be
'http://www.example.com/app/img/myImage.png'. A good app must take this into account.
Solution for ASP.NET MVC views
To get the root of the application, ASP.NET MVC provides the
UrlHelper class. To get the proper URL for the image in an MVC view, we’d be able to write
One solution is to generate an HTML element with the base URL on the MVC view that would be accessed by the referencing script. This could potentially be any element, e.g. the body, and the URL value could be stored in a
data-* attribute. For instance:
However, it turns out there’s an element specifically for this purpose - the
<base> HTML element.
So, a solution might look like this: