One of the useful features of working with server-side controls in ASP.NET is that you can use the '~' operator to create relative path references. For example, you can use a server-side Image control as follows:
<asp:Image runat="server" ImageUrl="~/images/mypic.gif" />
and it will resolve the imageurl reference to the root directory correctly. If this tag is referenced a level below the root, for example, it will resolve to src="../images/mypic.gif". You can even use this for some attributes in HtmlControls (including img and a):
<a href="http://www.blogger.com/~/default.aspx" runat="server"> </a>
As long as the control is server-side and the attribute is one that ASP.NET resolves to evaluate the '~' symbol, it works great. This is espcially useful for user controls and master pages, where you don't know beforehand where the control or page will be evaluated, and the path may well change.
As soon as you get used to this feature, however, you find places where it doesn't work, which is frustrating. For example, you might think that you could set the background property of the body element by making it a server-side control:
<body runat="server" background="~/images/mypic.gif">... (note - doesn't work)
But that won't work, since the body element maps to the generic HtmlGenericControl which has no fields that will be resolve the '~' symbol.
The solution I typically use to deal with this, is to call Page.ResolveClientUrl directly in th
e markup:
e markup:
<body background='<%= ResolveClientUrl("~/images/mypic.gif") %>' >...
This technique works well, although it does add some clutter to your page. What techniques have you used to deal with this issue?
No comments:
Post a Comment