Relative URLs in Sharepoint Web Parts

If you’re using STSDev for web part development, it becomes very simple to deploy files into the 12Hive (which in some circumstances is preferable to using embedded resources). As a consequence, it becomes tricky to create hyperlinks to resource files because:

  • you can’t guarantee the web part is sitting in root of the site collection (which would make for simple hyperlinks ala “_layouts/styles/myPart/myCSS.css”)
  • you can’t know that your site collection is located at the root of the web server (which would make for simply hyperlinks ala “_layouts/styles/myPart/myCSS.css”

So, to create simple relative urls from code (as opposed to using the <% $SPURL:~sitecollection/_layouts/styles/myPart/myCss.css %> approach) I used something I found on Ari Bakker’s website.

Deep underneath the SPContext object is a property called ServerRelativeUrl which is attached to the Site(SPWeb) and Site collection(SPSite) objects.

These can be used by the web part to refer to resource files deployed along with it. So, something like the following should work anywhere inside a site collection:

string cssLocation = SPContext.Current.Site.ServerRelativeUrl + “_layouts/styles/myPart/myCSS.css”;

Leave a Reply

Your email address will not be published. Required fields are marked *