asp.net-mvc - 是否可以在每页中捆绑脚本和样式

标签 asp.net-mvc bundling-and-minification

尽管捆绑是VS的一项巧妙功能,但有时我还是希望有一个脚本或CSS可供特定页面使用。这样,我可以确保避免名称冲突和/或覆盖。

是否可以捆绑文件,以便仅全局文件和页面特定文件可用?

例如,假设我有一个名为Cabinet.cshtml的页面。我也有Cabinet.jsCabinet.css文件。另一方面,我还有另一个名为AdminPanle.cshtml的页面,其中包含文件admin.jsadmin.css

现在,我希望这两个 View 只能访问其相应的文件,并且还可以访问jQuery和jQuery ui。因此,jQuery必须是全局的。

最佳答案

所以有什么问题?默认情况下,您的BundleConfig.cs中具有:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                    "~/Scripts/jquery-ui-{version}.js"));

因此,将这些捆绑包放在_Layout.cshtml的头上:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")

并创建其他4个捆绑包:
//scripts
bundles.Add(new ScriptBundle("~/bundles/cabinet").Include(
                    "~/Scripts/Cabinet.js"));
bundles.Add(new ScriptBundle("~/bundles/admin").Include(
                    "~/Scripts/admin.js"));
//styles
bundles.Add(new StyleBundle("~/Content/cabinet").Include("~/Content/Cabinet.css"));
bundles.Add(new StyleBundle("~/Content/admin").Include("~/Content/admin.css"));

现在,您可以分隔theese脚本和样式,并仅在需要的页面上添加它们。

另外,我认为最好在_Layout.cshtml标记的head中定义2个部分。
<head>
    //other scripts and styles here
    @RenderSection("scriptslib", required: false)
    @RenderSection("csslib", required: false)
</head>

因此,现在在您的Views(Cabinet.cshtmlAdminPanle.cshtml)中,您可以将库放置在它们应该像这样的位置:
@section scriptslib{
    @Scripts.Render("~/bundles/cabinet")
    }

关于asp.net-mvc - 是否可以在每页中捆绑脚本和样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33429945/

相关文章:

asp.net-mvc - 如果许多线程同时访问数据库的同一表,linqtosql是否会注意?

css - MVC 捆绑和 CSS 相对 URL

javascript - 样式表和脚本包在 Mono 中不起作用

asp.net-mvc - 如何调试缩小失败。返回未缩小的内容

jquery - 使用 ASP.NET 捆绑检查 jQuery 在 IE8 中失败

View 中的 ASP.NET Razor 模型语法

c# - ASP.net MVC - 在模型中处理 HTML 数据

c# - Jquery Ajax MVC Controller URL 问题

asp.net-mvc - Kendo UI 调度程序 : Custom view and edit behavior

cssmin 没有正确处理@import