gpt4 book ai didi

javascript - 在 ASP.NET MVC 中管理 js 和 css 文件

转载 作者:太空宇宙 更新时间:2023-11-04 13:20:33 25 4
gpt4 key购买 nike

我是 ASP.NET MVC 4 的新手,想知道 ASP.NET 包含 css 和 js 文件的方式是什么。

背景

在我的 PHP 元素中,我通常在 Controller 中使用 CSS 和 JS 文件名数组。这些数组在主模板中传递,其中一个函数循环遍历并为每个元素生成 html 标签,并在此时自动对它们进行版本控制。 CSS 位于 <head> 中而 JS 位于 </body> 之前标签。

我知道的事情

  1. BundleConfig(但是,我严格关注页面特定的 css/js 而不是全局的)
  2. 在文件列表中传递的类中创建一些静态函数,以相应地生成脚本和链接标签

问题

我应该如何设法从 View (甚至 Controller )中包含(并且可能像 BundleConfig 一样自动版本化和缩小)页面特定的 js 和 css 文件。?

最佳答案

一种选择是在您的布局页面中使用@RenderSection 来实现这一点。在布局页面中,您包括使用布局的所有页面共有的文件和/或包,并使用 @RenderSection 指定将包含页面特定文件的占位符(注意第二个参数 = false 使其可选)

布局页面

<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="~/Content/Common.css" rel="stylesheet" /> // Common .css files here
@RenderSection("styles", false) // Place holder for optional page specific .css files
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div id="content">
@RenderBody()
</div>
@Scripts.Render("~/bundles/jquery") // Common .js files or bundles
@RenderSection("scripts", required: false) // Place holder for optional page specific .js files or bundles
</body>
</html>

然后在页面中,定义页面特定包和/或文件的部分

@model ....
// Page specific html
@section styles {
<link href="~/Content/page-specific-stylesheet.css" rel="stylesheet" />
}
@section Scripts {
@Scripts.Render("~/bundles/page-specific-bundle")
<script src="~/Scripts/page-specific-file.js"></script>
<script type="text/javascript">
// page specific script
</script>

没有理由不能为页面特定文件创建包,即使它只有一个文件。优点是对于您的生产环境,文件将自动缩小(除非您在同一文件夹中已经有一个附加了 .min.js 的文件)。默认情况下, bundle 会缓存在浏览器中(我认为会缓存 12 个月),如果您编辑该文件,则会创建一个新的缩小版本,而旧版本会从浏览器缓存中删除。

关于javascript - 在 ASP.NET MVC 中管理 js 和 css 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24103199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com