【问题标题】:Getting jquery to work with MVC4让 jquery 与 MVC4 一起工作
【发布时间】:2013-09-23 19:04:47
【问题描述】:

这没有发生。我尝试将_Layout.cshtml中的脚本与<script src='@Content.Url("...正常链接,安装Web优化并使用捆绑包,并将@Scripts.Render()放在_Layout.cshtml的head/body/bottom和相关页面上的<script>标签之前。我错过了什么?

目录结构

Views
    Shared
        Js
            jquery-1.10.2.js
            jquery.color-2.1.2.min.js

BundleConfig.cs

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
        "~/Views/Shared/Js/jquery-{version}.js",
        "~/Views/Shared/Js/jquery.color-{version}.js")
    );
}

Global.asax.cs

protected void Application_Start()
{
    // blah, etc, then:
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

_Layout.cshtml

@Scripts.Render("~/bundles/jquery");

我可以在 JsFiddle 上运行实际的 javascript/jquery 代码,所以我在那里写的内容的有效性没有问题。

【问题讨论】:

  • 直接引用 jquery 而不使用 bundler(例如来自 CDN)是否有效?
  • HTML 输出是什么样的?
  • 为什么不把它们放在 Scripts 文件夹中?
  • @MichaelCwienczek 不,无论我是在 _Layout.cshtml 的头部还是在我正在使用的页面的正文中引用它们。
  • @ErikPhilips Oopes 无视我的最后回复!我看到 jquery 脚本以正确的方式链接(源路径是 Views/Shared/Js/jquery-1.10.2.js),但是在该位置找不到脚本的错误。

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


【解决方案1】:

BundleCollection 类有IgnoreList 属性,其中包含文件名的模式,不会被渲染。默认情况下,它会忽略带有min 字样的名称。您可以在RegisterBundles 中清除此列表:

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.IgnoreList.Clear();
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
        "~/Views/Shared/Js/jquery-{version}.js",
        "~/Views/Shared/Js/jquery.color-{version}.js")
    );
}

【讨论】:

    【解决方案2】:

    得到它的工作:我所做的只是将脚本移动到不同的文件夹Content/Js,并通过<script src='@Content.Url("... 链接它。 ContentViews 在同一目录级别。

    现在一切都很好,只是我不知道文件夹为什么重要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      • 2020-05-20
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多