2

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

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

我想知道最简单、最有效的方法是从局部视图中将内容添加到您的脑海中。

我需要这样做的原因是我在每个页面上都需要某些 java 脚本和 jquery,并且它因页面而异。我不只是想将它们全部添加到 _layout 视图中。

4

2 回答 2

15

您可以使用部分来执行此操作。例如:我有两个以上的视图,它们彼此具有相同的 _Layout。公司控制器中的我的索引操作具有以下部分:

@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 控制器中的显示操作具有相同的部分,但不同的 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>
于 2013-07-14T18:37:40.523 回答
1

在您的 _Layout.cshtml 页面(或任何其他母版页)上,在标签内部使用以下代码<head></head>

@if (IsSectionDefined("SpecialOther"))
{
    @RenderSection("SpecialOther")
}

在您想要特殊 css、脚本或任何其他项目的页面上,指定它们的引用。例如,

    @section SpecialOther{
        <link href="~/css/responsive-tables.css" rel="stylesheet" />
  <script src="~/js/datatables/extras/ZeroClipboard.js"></script>
    }
于 2013-12-14T09:32:40.020 回答