Tuesday, April 26, 2005 7:06:24 PM UTC :: Filed Under ASP.NET

The Problem:

You just built a user control (.ASCX) that is a header template for your web site.  The user control contains some ‘root sensitive’ information, like the path to an image, the path to a linked JavaScript file, the path to a linked CSS file, etc.   You’d like to use relative file paths, but you already know that you can’t prefix the file path with “/” because your developing the site in a Virtual Directory on your Windows XP machine.  Prefixing a relative URL with “/” will take you to the root of the web site, not the root of the Virtual Directory.

So, what do you do to make sure the file paths always work no matter where your user control is placed in the directory structure?

One option is to append <%= Request.ApplicationPath %> before all of your URLs to automatically insert the name of the Virtual Directory into the path.  (This is used in the Microsoft iBuySpy Portal solution.)  For example, if you wanted to link to your Style Sheet in the header, the HTML would look like this:

<link href="<%= Request.ApplicationPath %>/CSS/Screen.css"
type="text/css" rel="stylesheet">

However, once you move your site from your development machine to a live web server where your site will most likely be located in the root directory, the above code will fail.  Well, it will work, but the path to the Style Sheet will end-up being:

//CSS/Screen.css

Note the double forward slashes.  Request.Application path returns “/” when ever the site is at the root directory.  Some browsers will choke on a URL with two forward slashes in it.

Ok, so that was lame.   Are we just screwed?

The Solution: (Well, the best one I’ve found so far)

When inserting images into a User Control, it’s probably easiest to just use the ASP.NET Image Control.  If you prefix the ImageURL in an Image Control with “~/”, the Image Control will automatically find the root directory for you.

That’s all fine-and-dandy, but what if you’re not working with an image?  Well, after much research, I found-out the secret method being used by the image control is ResolveURL().  With ResolveURL(), you can insert the path to any file and get the root directory.  For example, let’s go back to our Style Sheet example from above.  If you replace the Request.ApplicationPath with ResolveURL, your problem is solved:

<link href="<%=ResolveURL("~/CSS/Screen.css") %>"
type="text/css" rel="stylesheet">

Note that you’ll still need to prefix the URL with “~/”.   Granted, this isn’t the prettiest solution, and image won’t show-up in design time (I hate that), but at least it works!

Comments are closed.
Navigation
On this page....
Search
Archives
<February 2012>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910
Categories
Contact me
Send mail to the author(s) Contact Todd M. Taylor