【问题标题】:MVC 4 - Script/Css Rendering ProblemsMVC 4 - 脚本/Css 渲染问题
【发布时间】:2014-01-16 17:49:58
【问题描述】:

我在浏览器控制台中收到以下错误消息:

GET http://*:54559/Scripts/ 403(禁止)

http://:54559/Content/css/ 400(错误请求)

未捕获的引用错误:$ 未定义

在我的 _Layout.shtml 中,我使用以下代码尝试包含 css/bootstrap。

@Styles.Render("~/Content/css/*")

<!-- JavaScript -->
@Scripts.Render("~/Scripts/")
@RenderSection("scripts", required: false)

<script>
    // Activates the Carousel
    $('.carousel').carousel({
        interval: 5000
    })
</script>

文件路径看起来不错,因为在我的项目中,css 位于“Content/css”,而脚本只是顶层的一个名为“Scripts”的文件夹

有什么想法吗?

【问题讨论】:

  • 你在BundleConfig.cs中添加脚本了吗?
  • 没有任何捆绑包
  • 点击 Chris 回答中的链接。您需要创建一个包,然后@Scripts.Render 将包含那些添加到包中的脚本。

标签: c# jquery css asp.net-mvc razor


【解决方案1】:

~/Content/css/~/Scripts/ 不是文件路径。它们是捆绑包名称,因此如果您没有捆绑包文件,请按照以下步骤操作:

在您的 App_Start 文件夹中添加一个 BundleConfig 类:

 public class BundleConfig
 {

 }

像这样添加RegisterBundles 方法:

public static void RegisterBundles(BundleCollection bundles)
{

}

然后你可以添加一个包,把这段代码写到你的方法中:

 bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

这里~/Content/css 是您的Bundle Name~/Content/site.css 是您的 Css 文件路径。如果您的 css 文件位于不同的路径中,请更改它。

现在还有一步,打开您的 Global.asax 文件并将此代码添加到您的 Application_Start 中:

BundleConfig.RegisterBundles(BundleTable.Bundles);

然后您可以使用以下方式渲染您的 Bundle:

@Styles.Render("~/Content/css")

您还可以使用一个包渲染多个文件,为此在此处添加所有文件路径,如下所示:

bundles.Add(new StyleBundle("~/Content/css")
.Include("~/Content/site.css",
         "~/Content/sample.css",
         "~/Content/sample2.css"));

PS:你也可以看看这个关于使用 Bundles 的好处的问题:Usage of the ASP.NET MVC4 jquery/javascript bundles

【讨论】:

    【解决方案2】:

    MVC 正在寻找 Bundles,这是您要在您的站点中使用的脚本和 CSS 文件的列表。

    App_Start\BundleConfig.cs查看您的捆绑注册文件

    确保您的捆绑包名称与您传递给 ScriptsStyles 的内容相对应。

    http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

    【讨论】:

    • 啊,我什至没有 bundleconfig.cs 文件
    • 现在您有机会了解捆绑包,那么 :) 它们是各种很棒的酱料!
    猜你喜欢
    • 2013-01-22
    • 2014-04-27
    • 2015-04-13
    • 2012-05-28
    • 2020-04-19
    • 2023-03-21
    • 2021-06-24
    • 2011-05-19
    • 1970-01-01
    相关资源
    最近更新 更多