gpt4 book ai didi

asp.net - 嵌套 Razor 模板中的 @RenderSection

转载 作者:行者123 更新时间:2023-12-03 08:25:10 25 4
gpt4 key购买 nike

我的问题是我似乎无法使用 @RenderSection来自嵌套模板时 @RenderSection在基本模板中定义。目前,我有一个嵌套的基本模板,它链接到一个子模板,然后在 View 页面中使用。当我定义 @RenderSection在基本模板中并在 View 页面中呈现它会引发错误。

这是确切的问题。

我想创建一个 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 .

我是否需要在 View 页面中包含指向基本模板的指针?
@{
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>

最佳答案

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

基础模板.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()

如果您将渲染部分放在基础模板的某个部分内,它将在基础模板上的正确位置渲染该部分。

View.cshtml -> 使用 MiddleLayout.cshtml 作为布局
@section HeaderContent
{
<!-- header content that will now render -->
}

<!-- page content -->

关于asp.net - 嵌套 Razor 模板中的 @RenderSection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8578843/

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