One common problem I’ve faced when developing applications is when I need to access an Image file or some other artifact that is relative to my website.
I’ve often gotten “lucky” where my virtual directory path locally matches my QA, Staging, Production, etc. So I’m able to have javascript code like this:
Here, I’m assuming that my images will always be stored somehow like this:
http://localhost/Content/Images
http://[test-dns]/Content/Images
http://[prod-dns]/Content/Images
etc…
That above javascript will fail if I am forced to be put into a Virtual Directory such as this:
http://[prod-dns]/[some-virtual-directory]/Content/Images
The most effective way I’ve found to get around this is by creating a hidden field on my main master page that contains the value derived by the web server of the root URL to my website. This root URL might contain no virtual directory or 10 virtual directories depending on the IIS Web Server set up.
I’m using ASP.NET MVC, but this example can easily be ported into a Page_Load event with standard ASP.NET web forms.
Just place that code somewhere in the body of your master page.
Then access it via JQuery, or standard javascript using something like this:
Then finally you’re javascript might look something like this to get at your actual Image source.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.