The solutions I saw so far didn't work in my project (especially not for .css links). The issues were the following:
- inside
<link>
it didn't resolve the <%=...%>
expression
- it did not find the Page.ResolveURL in all cases
- there was some trouble with ' and " quotes if you embedd
<%=...%>
So I'd like to offer this solution: In code behind (your master page's C# class), add the the following 3 methods:
public partial class SiteBasic : System.Web.UI.MasterPage
{
public string ResolveURL(string url)
{
var resolvedURL=this.Page.ResolveClientUrl(url);
return resolvedURL;
}
public string cssLink(string cssURL)
{
return string.Format("<link href='{0}' rel='stylesheet' type='text/css'/>",
ResolveURL(cssURL));
}
public string jsLink(string jsURL)
{
return string.Format("<script src='{0}' type='text/javascript'></script>",
ResolveURL(jsURL));
}
}
For stylsheet references, you can then say:
<%=cssLink("~/css/custom-theme/jquery-ui-1.8.20.custom.css")%>
For JavaScript references, it looks like so:
<%=jsLink("~/Scripts/jquery-1.7.2.js")%>
And for other references, you can use:
<a href='<%=ResolveURL("~/Default.htm")%>'>link</a>
<img title='image' src='<%=ResolveURL("~/Images/logo.png")%>'/>
Note: I found it is better to use single quotes outside and double quotes inside the href or src attribute as shown in the example above. Doing it vice versa caused trouble in some cases as I found.
This solution is simple and it worked well in my case, even if the pages referencing the master page reside in different subdirectories. What it basically does is translating the ~
path (which needs to be absolute from the root of your web site) into a relative path (using as many ../
in the path as needed) based on the page you're currently displaying.
Advanced hint:
If you're using AJAX calls to invoke web service methods, then you'll have the same issue referencing them if you have ASPX pages on different directory levels. I recommend you define something like (assuming that your web services reside in the directory ~/AJAX
):
<script type="text/javascript">
function getWebServicePath() { return '<%=ResolveURL("~/AJAX/")%>'; }
</script>
inside the <head> ... </head>
section of your master page. This will make the entry path of the web service available in your JavaScript. You can use it like
$.ajax({
type: "POST",
url: getWebServicePath()+"myWebService.asmx/myMethod",
data: $.toJSON({ param: "" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// ... code on success ...
},
error: function (ex) {
// ... code on error ...
}
});