learn forever RSS 2.0
# Monday, May 03, 2010

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:

  1. $('.ok-button').attr('src', '/Content/Images/btn_ok.jpg');
  2. $('.ok-button').hover(
  3.     function() { $(this).attr('src', '/Content/Images/btn_okOver.jpg'); }
  4.   , function() { $(this).attr('src', '/Content/Images/btn_ok.jpg'); }
  5. );

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.

  1. <% string virtualPath = HttpRuntime.AppDomainAppVirtualPath;
  2.        virtualPath = virtualPath.EndsWith("/") ? virtualPath : virtualPath + "/";
  3.     %>
  4.     <input id = "website-image-path" type = "hidden" value = '<%=virtualPath + "Content/Images/" %>' />

Just place that code somewhere in the body of your master page.

Then access it via JQuery, or standard javascript using something like this:

  1. $('#website-image-path').val();

Then finally you’re javascript might look something like this to get at your actual Image source.

  1. var websiteImagePath = $('#website-image-path').val();
  2. $('.ok-button').attr('src', websiteImagePath + 'btn_ok.jpg');
  3. $('.ok-button').hover(
  4.     function() { $(this).attr('src', websiteImagePath + 'btn_okOver.jpg'); }
  5.   , function() { $(this).attr('src', websiteImagePath + 'btn_ok.jpg'); }
  6. );
Monday, May 03, 2010 3:54:25 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] - Trackback
ASP.Net MVC | Deployment | JQuery
Dave Arlin
Archive
<May 2010>
SunMonTueWedThuFriSat
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Dave Arlin
Sign In
Statistics
Total Posts: 9
This Year: 2
This Month: 0
This Week: 0
Comments: 0
All Content © 2010, Dave Arlin
DasBlog theme 'Business' created by Christoph De Baene (delarou)