Monday, September 14, 2009

Relative path issue with client tags ( ~ is not working )

You can continue using a client tag such as <img>, <link>, etc. with the "~" tilde with below solution.


You just need to use the System.Web.VirtualPathUtility.ToAbsolute("~") method to convert the ~ to the Application Path.


So, if your file is located at "~/images/default.jpg" and you need to specify this path in a client tag like <img>, ASP.NET would not allow you to use this path unless you use a Server Control like <asp:Image>.


To continue using the client tag you can use:
<img src="<%=System.Web.VirtualPathUtility.ToAbsolute("~")%>/images/ default.jpg" />


This would be resolved to "/MyApplication/images/default.jpg" where the first forward slash (/) stands for the WebSite root. Thus, the tilde "~" is effectively resolved to "/MyApplication"


Alternatively, Control.ResolveClientUrl can be used. For example,


<img src='<%= ResolveClientUrl("~/images/default.jpg")%>' />

1 comment:

  1. It is really new and helpful coding technique for me.. thanks for sharing such knowledge

    ReplyDelete