Well, i understand my title is a bit confusing. I will state it clearly below with the example.
<asp:ImageButton ID="imgButton" NavigateUrl="~/Presentation/Resources/Images/addFile.png" runat="server" />
In html, the control above will be rendered as
<input type="image" name="imgButton" id="imgButton" src="../../Resources/Images/addFile.png" style="border-width:0px;">
I notice that,it will convert the src from "~" to "../../" .It auto arrange it will the file level.
so in javascript, i want to set it the control with this url :
~/Presentation/Resources/Images/PDF.png
unfortunately, in html it will be rendered as
<input type="image" name="imgButton" id="imgButton" src="~/Presentation/Resources/Images/addFile.png" style="border-width:0px;">
My question is, What should i write if i wanna get the "../../" relative path with "~" ? I have tried this,but i cant get it.
<script type="javascript">
document.getElementById("<%= imgButton.ClientID %>").src =
"~/Presentation/Resources/Images/PDF.png";
</script>
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With