views:

398

answers:

1

I wrote a javascript method to display an image dynamically depending on whether or not a plugin is installed or not. Depending on the page, the url might be deep into sub paths and i wanted to see if i can get a path back to the image without all the marky-mark.

Example

myImage src location = {root}/Content/Images/myImage.png

Now call the js to display the image on the following pages. I show the path of the example page and the image element with the src path. Notice how its different depending on how deep we are. If i use an absolute path, then i would have to change it for my test environment and production. I thought I could use ~ but i guess not. Ideas ?

http://mysite.com/sub1/sub2/ -- <img src="../../Content/Images/myImage.png" />

http://localhost:2500/sub1/ -- <img src="../Content/Images/myImage.png" />

+2  A: 

The tilde is only relevant for .NET server side code.

An easy way to accomplish what you're looking for is to write the root path out to a javascript variable or function.

For example on the server side on your page:

public string RootPath
{
  get
  {
     return ResolveUrl("~/");
  }
}

And then use the following javascript:

<script type="text/javascript">
<!--
function getRoot()
{
   return '<%= RootPath %>';
}
// -->
</script>

You can then use the javascript getRoot function to get to the root of the website and use it for your urls.

Brian Hasden
Yea I figured that out.
gmcalab
Should this work then ?<%= Url.Content("~/Content/Images/myImage.png") %>
gmcalab
Possibly, I'd have to see it in context, but you're probably on the right path. Something similar to what you're trying to do that's usuing Url.Content is available at http://ericdotnet.wordpress.com/2009/03/17/jquery-ui-tabs-and-aspnet-mvc/. Let me know if that helps at all.
Brian Hasden
I am using asp.net MVC... and when I use the Url.Content, it doesnt work actually. Here's what I have to test it ... alert('<%= Url.Content("~/Content/Images/myImage.png") %>');
gmcalab
I'm not very familiar with the asp.net MVC framework, but this url might help: http://msdn.microsoft.com/en-us/library/ms178116.aspx. For example, you should be able to use Request.ApplicationPath or something similar to get you that root path you need.
Brian Hasden