Well, i understand my title is a bit confusing. I will state it clearly below with the example.
Actually, URLs with tilde get converted to absolute URL thanks to the methods : ResolveURL and ResolveClientURL
Therefore you should be able to do this :
<input type="image" name="imgButton" id="imgButton" src="<%=this.ResolveClientUrl("~/Resources/Images/addFile.png")%>" style="border-width:0px;">
(this is actually done automatically for you in Web Controls like HyperLink and such)
The big difference with those two methods happens when you use User-controls. In a case, the URL refers to the URL relative to the folder where the user-control is, in the other case, that would be the page containing the user-control.
See also this question : Control.ResolveUrl versus Control.ResolveClientUrl versus VirtualPathUtility.ToAbsolute
Try this: http://weblogs.asp.net/joelvarty/archive/2009/07/17/resolveurl-in-javascript.aspx
In the master page for the site, put this:
<script type="text/javascript">
var baseUrl = "<%= ResolveUrl("~/") %>";
</script>
Then, in your javascript file, put this function:
function ResolveUrl(url) {
if (url.indexOf("~/") == 0) {
url = baseUrl + url.substring(2);
}
return url;
}
You could have put the function right in the master page, but then you wouldn’t get intelli-sense on it for the rest of your code. Now you can call ResolveUrl with ~/ right from javascript.
Why do you need this on clientside? Use servercontrols(runat=server
) and you can use tilde to resolve URL on server.
Have a look at the VirtualPathUtility Class and this information from msdn about ASP.NET project paths.
The VirtualPathUtility.ToAppRelative method is probably what you're looking for.
VirtualPathUtility.ToAppRelative
If the virtual path for the application is "myapp" and the virtual path "/myApp/sub/default.asp" is passed into the ToAppRelative method, the resulting application-relative path is "~/sub/default.aspx".
It explains and gives examples on how to convert between different path formats.
I also think you should to output the correct path at server level instead of reverse engineering in javascript in the browser. It may cause issues if you rearrange your project and asp changes it.
WebControls translate the tilde into the correct path when run on the server before rendering the html, you will need to use the full path or relative path in jQuery if you're changing the src on the fly.
You might want to have a property on the page with the root path eg: ApplicationRootURL and do something like this:
<script type="javascript">
document.getElementById("<%= imgButton.ClientID %>").src =
"<%=ApplicationRootURL%>/Presentation/Resources/Images/PDF.png";
</script>