我发现了一些与此相关的问题,但通常有很多不同的答案,而且它们看起来都非常困惑和复杂。
如果那是需要做的,那么好吧,我最好坐下来解决它。
我想知道最简单、最有效的方法是从局部 View 向您的头部添加内容。
我需要这样做的原因是我需要在每个页面上使用特定的 java 脚本和 jquery,并且它因页面而异。我不想将它们全部添加到 _layout View 中。
最佳答案
您可以对部分执行此操作。例如: 我有两个以上的 View ,它们彼此具有相同的_Layout。我在公司 Controller 中的索引操作有如下部分:
@model Invoice.Model.HelperClasses.CompanyViewModel
@{
ViewBag.Title = "Companies";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@section usage{
<link href="~/css/uniform.default.css" rel="stylesheet" />
}
@section other{
<link href="~/css/datepicker.css" rel="stylesheet" />
<link href="~/css/SimpleSlide.css" rel="stylesheet" />
<link href="~/css/responsive-tables.css" rel="stylesheet" />
}
@section script
{
<script src="~/js/datepicker/bootstrap-datepicker.js"></script>
}
Invoice Controller 中的 Display Action 具有相同的部分,但不同的 css 和 js 如下:
@model Invoice.Model.HelperClasses.InvoiceViewModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@section usage{
@*<link href="~/css/uniform.default.css" rel="stylesheet" />*@
}
@section other{
<link href="~/css/DT_bootstrap.css" rel="stylesheet" />
<link href="~/css/responsive-tables.css" rel="stylesheet" />
<script src="~/js/datatables/extras/ZeroClipboard.js"></script>
}
@section script
{
<script src="~/js/datepicker/bootstrap-datepicker.js"></script>
<script src="~/js/validate/jquery.metadata.js"></script>
<script src="~/js/validate/jquery.validate.js"></script>
}
然后您可以在 _Layout 中使用此部分,但其所需参数应为 false。看看:
<!DOCTYPE html>
<html>
<head>
<!--usage-->
@RenderSection("usage", required: false)
<!--other-->
@RenderSection("other", required: false)
<!--script-->
@RenderSection("script", required: false)
<head>
<body>
</body>
</html>
关于asp.net-mvc-4 - 从局部 View 向 View 头部添加 css、js 或其他内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48283336/