UPDATE: Included simple SiteMap support in sample here.

If you’ve played with the new ASP.NET routing stuff with WebForms, you probably encountered some issues with relative paths to static content (css, Javascript files etc).  This is a common issue across browsers because of the way they resolve relative paths.  Here’s an example:

    <script src="Javascript/TestScript.js" type="text/javascript"></script>

 

Let’s say this was in a page called Index.html.  Your browser request might look like this:

http://www.chriscavanagh.com/Chris/SimpleRoutingTest/Index.html

After grabbing the page content, the browser would see the relative path to TestScript.js and (reasonably) assume it could retrieve it from here:

http://www.chriscavanagh.com/Chris/SimpleRoutingTest/Javascript/TestScript.js

However, in our case we’ve thrown some funky URL routing into the mix.  Here’s how we want to hit our page:

http://www.chriscavanagh.com/Chris/SimpleRoutingTest/Search/42

Assume for now we’ve defined a Route to divert that to Index.html (in Global.asax):

routes.Add( new Route( "Search/{category}", new WebFormRouteHandler( "~/Index.html" ) ) );

 

The routing works as expected, but when the browser tries to get TestScript.js, here’s where it’ll go looking:

http://www.chriscavanagh.com/Chris/SimpleRoutingTest/Search/Javascript/TestScript.js

Fortunately there are some simple ways to fix this :) (note you may need to adapt these slightly to your specific case):

  • Use ASP.NET themes and keep Javascript in embedded resources.  The theme mechanism takes care of paths nicely; it knows how to find everything from the application root and "just works".  Make Javascript files embedded resources and use ScriptManager.RegisterClientScriptResource to serve them up automatically through ScriptManager.axd.
  • Use the <base> element in your page and set its href to an absolute URL.  This can go in each page, or just in you Master page(s) if you use them.  You could add code similar to this:
    public string BaseUrl
    {
        get { return Request.Url.GetLeftPart( UriPartial.Authority ) + VirtualPathUtility.ToAbsolute( "~/" ); }
    }
    
     
  • Then make your <base> element look like this:
    <base href="<%= BaseUrl %>" />
    

    That should give you an absolute URL to your application root.  As long as all paths are relative to that, everything should work nicely :)

    I’ve updated my "Simple Routing Test" site to show this in action (source available here).  In this case the BaseUrl helper (above) is in the RoutablePage class.  Each page shows a bunch of links (dynamically generated against the defined routes).  At the bottom you should see "Hello from Javascript" with a yellow background.  The yellow signifies the CSS is working, and the text shows it’s successfully invoked a Javascript function :)

Hope this helps! :)

About these ads