views:

46

answers:

2

I have some jQuery that writes some image tags to the browser, but I want to reference them such that I don't have to hardcode the path, and I'm not able to use relative paths either. This is a .NET application, and I am trying to use server side tags.

So, I changed the following:

$('#IMG_' + myID).attr('src','../images/plus.gif');

to:

$('#IMG_' + myID).attr('src','<%= Url.Content("~/images/plus.gif") %>');

or:

$('#IMG_' + myID).attr('src','<%= ResolveUrl("~/images/plus.gif") %>');

When it runs I get javascript errors, Invalid argument on line 48, char 325 of jquery-1.4.2.min.js.

+1  A: 

If you're not using virtual directories on any environment you could just use /images/plus.gif

If your site has an url like this localhost/mysite/default.aspx it won't work

Claudio Redi
I tried just /images/plus.gif, but that did not work. What does work is /PROJNAME.Web/images/plus.gif. Is there any time when the /PROJNAME.Web/ would cause an issue?
Sephrial
+1  A: 

Here's something I've done in a couple projects. It's designed to be used with ASP.NET MVC, but I imagine it could be adopted to use with WebForms as well.

script: common.js

function Environment() { }    
Environment.vroot = '';

Environment.getUrl = function(path) {
    return Environment.vroot + path;
};

partial view/user control: CommonScript.ascx

<script type="text/javascript">
    Environment.vroot = '<%= Url.Content("~/") %>';
</script>

I just put CommonScript.ascx on my master page, but you can put it wherever you want. It needs to be rendered after the script reference to common.js though.

If you use this, you can just do this to set your image url:

$('#IMG_' + myID).attr('src', Environment.getUrl('images/plus.gif'));
Daniel Schaffer
This works for me. this is the same pattern I am using on the ASP.NET side. I think I will use this for now on. Thx!
Sephrial