asp.net – @RenderSection在嵌套剃刀模板

我的问题是我不能使用@RenderSection从嵌套模板当@RenderSection在基本模板中定义。目前,我有一个嵌套基本模板,它链接一个子模板,然后在视图页面中使用。当我在基本模板中定义@RenderSection并在视图页面中渲染它时会抛出一个错误

这是确切的问题。

我想创建一个RenderSection允许我插入自定义脚本。
我的基本模板….

<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
 @RenderSection("HeaderContent",false) // The region of the header scripts (custom css)

</head>
<body>
@RenderBody()
</body>
</html>

然后我跳过子模板,因为我不想把任何自定义头部代码在那里,并应用到页面本身。

@section HeaderContent {
    <script>alert("hi");</script>
}

我的问题是,我似乎不能添加自定义头部代码到基本模板从我的正常页面

以下部分已定义,但尚未呈现布局页〜/ Views / Shared / OneColLayer.cshtml“:”HeaderContent。

我需要在视图页面包括一个指向基本模板的指针吗?

@{
    Layout = "~/Views/Shared/BaseTemplate.cshtml";
}

我的新基本模板

<head>
  <link rel="stylesheet" type="text/css" href="@Url.Content("~/content/layout.css")" />
  <link rel="stylesheet" type="text/css" href="@Url.Content("~/content/global.css")" />
  <script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"></script>
  <script type="text/javascript" src="@Url.Content("~/js/fadeInFadeOut.js")"></script>
  <title>@ViewBag.Title</title>
  @RenderSection("HeaderContent",false)
</head>
<body>
  @RenderBody()
</body>

我的新子模板

@{
  Layout = "~/Views/Shared/BaseTemplate.cshtml";
}
@RenderSection("HeaderContent",false)
@RenderBody()

我的看法

@{
  ViewBag.Title = "Home";
  Layout = "~/Views/Shared/OneColLayer.cshtml";
}
@section HeaderContent {
  <h1>Left Content</h1>
}
<div>my view content</div>

内容被放置在oneCol模板现在的基本模板中。

结果…

<div id="Content">
   <h1>Left Content</h1>
</div>

解决方法

您需要指定允许在中间模板中传递的部分。

BaseTemplate.cshtml

<!DOCTYPE html>
<html>
  <head>
    <title>@ViewBag.Title</title>
    @RenderSection("HeaderContent",false) @* The region of the header scripts (custom css) *@
  </head>
<body>
  @RenderBody()
</body>
</html>

编辑

您的新子模板

@{
  Layout = "~/Views/Shared/BaseTemplate.cshtml";
}
@section HeaderContent {
  @RenderSection("HeaderContent",false)
}
@RenderBody()

如果将render部分放在基本模板的某个部分内部,它将在基本模板上将该部分呈现在正确的位置。

View.cshtml – >使用MiddleLayout.cshtml作为它的布局

@section HeaderContent
{
    <!-- header content that will Now render -->
}

<!-- page content -->

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....