尽管捆绑是VS的一项巧妙功能,但有时我还是希望有一个脚本或CSS可供特定页面使用。这样,我可以确保避免名称冲突和/或覆盖。
是否可以捆绑文件,以便仅全局文件和页面特定文件可用?
例如,假设我有一个名为Cabinet.cshtml
的页面。我也有Cabinet.js
和Cabinet.css
文件。另一方面,我还有另一个名为AdminPanle.cshtml
的页面,其中包含文件admin.js
和admin.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.cshtml
和AdminPanle.cshtml
)中,您可以将库放置在它们应该像这样的位置:@section scriptslib{
@Scripts.Render("~/bundles/cabinet")
}
关于asp.net-mvc - 是否可以在每页中捆绑脚本和样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33429945/