ASP.NET – path to use to reference .CSS and .JS

I have a Master Page in the root of my project. I have Content Pages throughout my project and in subfolders referencing this Master Page. What is the correct way to reference my .CSS and .JS files if I always want them to be relative to the root?

Here is how I’m doing it now:

link href="/common/css/global.css" rel="nofollow noreferrer noopener"
script src="/common/javascript/global.js"

But that breaks the link. I tried without the leading “/” but that didn’t work on my pages in the subfolders.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I would use something like

Server.ResolveClientUrl("~/common/css/global.css")

This will get a proper url for you at all times.

Example:

Per the comment this would be full usage.

<link type="text/css" rel="stylesheet" 
    href='<%= Server.ResolveClientUrl("~/common/css/global.css") %>' />

According to comments, other validated usage, no “error CS1061: ‘System.Web.HttpServerUtility’ does not contain a definition” error:
    <script type="text/javascript" 
src="<%= Page.ResolveUrl("~/Scripts/YourScript.js") %>" ></script>

Also is important to always put the closing tag .

Method 2

You can make the <link> tag to run at server so Asp.Net will resolve the URL for you like this:

<link href="~/common/css/global.css" rel="nofollow noreferrer noopener" runat="server" />

(Notice the ‘~’)
I don’t know if it can be applied to the <script> tag though, you should try…

EDIT: I discovered recently on a project that you can (and should) use a ScriptManager to hold your scripts (you can only have 1 per page). You can put one in your MasterPage and reference all your scripts. Inside your content page, you then add a ScriptManagerProxy that will ‘reference’ the scripts on the master page and you can even add other scripts for that content page only.

Method 3

I do it as simple as this: link href="<%=ResolveUrl(" rel="nofollow noreferrer noopener"~/common/css/global.css")%>"

Method 4

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 ...
    }
});


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x