C# ASP.NET - 用于引用 .CSS 和 .JS 的路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/735684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:10:00  来源:igfitidea点击:

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

javascriptc#jqueryasp.net

提问by Mike Cole

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?

我的项目根目录中有一个母版页。我在整个项目和引用此母版页的子文件夹中都有内容页面。如果我总是希望它们与根相关,那么引用我的 .CSS 和 .JS 文件的正确方法是什么?

Here is how I'm doing it now:

这是我现在的做法:

link href="/common/css/global.css"
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.

但这打破了联系。我尝试不使用前导“/”,但这在我的子文件夹中的页面上不起作用。

采纳答案by Mitchel Sellers

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:

根据评论,其他经过验证的用法,没有“错误 CS1061: 'System.Web.HttpServerUtility' 不包含定义”错误:

    <script type="text/javascript" 
src="<%= Page.ResolveUrl("~/Scripts/YourScript.js") %>" ></script>

Also is important to always put the closing tag .

始终放置结束标记也很重要。

回答by Julien Poulin

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

你可以让<link>标签在服务器上运行,这样 Asp.Net 就会像这样为你解析 URL:

<link href="~/common/css/global.css" runat="server" />

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

(注意'~')
我不知道它是否可以应用于<script>标签,你应该尝试......

EDIT: I discovered recently on a project that you can (and should) use a ScriptManagerto 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 ScriptManagerProxythat will 'reference' the scripts on the master page and you can even add other scripts for that content page only.

编辑:我最近在一个项目中发现您可以(并且应该)使用 aScriptManager来保存您的脚本(每页只能有 1 个)。您可以在 MasterPage 中放置一个并引用所有脚本。在您的内容页面中,您然后添加一个ScriptManagerProxy将“引用”母版页上的脚本,您甚至可以仅为该内容页面添加其他脚本。

回答by Stefan Bergfeldt

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

我这样做很简单: link href="<%=ResolveUrl("~/common/css/global.css")%>"

回答by Matt

The solutions I saw so far didn't work in my project (especially not for .css links). The issues were the following:

到目前为止我看到的解决方案在我的项目中不起作用(特别是不适用于 .css 链接)。问题如下:

  • 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 <%=...%>
  • <link>它里面没有解析<%=...%>表达式
  • 它在所有情况下都没有找到 Page.ResolveURL
  • 如果您嵌入 ' 和 " 引号,则会出现一些问题 <%=...%>

So I'd like to offer this solution: In code behind (your master page's C# class), add the the following 3 methods:

所以我想提供这个解决方案:在后面的代码(您的母版页的 C# 类)中,添加以下 3 个方法:

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 stylsheetreferences, you can then say:

对于样式表引用,您可以说:

<%=cssLink("~/css/custom-theme/jquery-ui-1.8.20.custom.css")%>

For JavaScriptreferences, it looks like so:

对于JavaScript引用,它看起来像这样:

<%=jsLink("~/Scripts/jquery-1.7.2.js")%>

And for otherreferences, 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.

注意:我发现最好在 href 或 src 属性外使用单引号和双引号,如上例所示。正如我发现的那样,在某些情况下,反之亦然会造成麻烦。

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):

如果您使用AJAX 调用来调用 Web 服务方法,那么如果您在不同目录级别上有 ASPX 页面,您将遇到同样的问题。我建议您定义类似的内容(假设您的 Web 服务位于目录中~/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

母版页<head> ... </head>部分内。这将使 Web 服务的入口路径在您的 JavaScript 中可用。你可以像这样使用它

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