Use Site Url in SharePoint

There are several ways to reference site collection or site url in masterpage, layout page, application page and web parts.

1. Token: ~sitecollection ~siteThese tokens only works with SharePoint server side controls. They do not work with ASP.NET control or HTML control.2. SharePoint Server Token <% $SPUrl:~sitecollection/…%>This token is only available for SharePoint Office Server not the SharePoint Foundation Server and it only works with a few SharePoint server controls.If it doesn’t work, you can use asp.net letral control to work around as

3. Emedded Code: <%=SPContext.Current.Site.ServerRelativeUrl %>You can use the embedded code any where in application page and web parts but don’t use it in master page and page layout even though they seem work, because master page and page layout can be customized. The embedded code is only allowed in the uncustomized pages.

4. SharePoint Control: <SharePoint:ProjectProperty Property=”Url” runat=”server”/>You can use the value returned by this control as control attribute but this is more like an hack, but it works.If you don’t want to use it directly in attribute, you can use asp.net leteral control like this

<asp:literal runat=”server” Text=”&lt;link href=’”/> <SharePoint:ProjectProperty Property=”SiteUrl” runat=”server” /> <asp:literal runat=”server” Text=”/Style Library/My Branding/MyStyles.css’ rel=’stylesheet’ type=’text/css’/&gt;”/>Here is when to use which option with different controls1. <SharePoint:ScriptLink>The only way works for ScripLink is the token ~sitecollection

Conclusion:When you need to reference site collection url such as /sites/hr/…, try the token “~sitecollection” first. If it doesn’t work, try the SharePoint Office Server token “<% $SPUrl:~sitecollection/…%>”.As last resort, try the control <SharePoint:ProjectProperty Property=”Url” runat=”server”/> as control attribute value or combine it usage with literal control.