asp.net-mvc-4 - 从局部 View 向 View 头部添加 css、js 或其他内容

标签 asp.net-mvc-4 partial-views

我发现了一些与此相关的问题,但通常有很多不同的答案,而且它们看起来都非常困惑和复杂。

如果那是需要做的,那么好吧,我最好坐下来解决它。

我想知道最简单、最有效的方法是从局部 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/

相关文章:

jquery - 模型和列表框

json - 为 ASP .NET MVC 4 WebAPI 序列化 (XML/JSON) 更改内部对象的名称

javascript - Rails js 在清除之前的模板后渲染部分内容

ruby-on-rails - ruby rails : conditionally display a partial

c# - 如何使用 Ajax.BeginForm 更新 div 并执行 javascript 函数?

asp.net-mvc-4 - Chrome 中的捆绑和缩小问题,但在 Mozilla 中运行良好

c# - "SaveChanges() "方法错误

asp.net-mvc - 如何在ASP.NET MVC应用程序区域中使用不同的 Entity Framework DbContext?

asp.net-mvc - 验证在部分 View 中不起作用

javascript - 从 ASP.NET MVC 部分 View 中卸载/删除 javascript 函数