【发布时间】:2018-02-23 06:53:44
【问题描述】:
我试图了解 Razor 视图中部分的工作原理。我有 2 个布局文件:_Layout.cshtml 和 _LayoutChild.cshtml,它们使用内部的第一个布局。我尝试在_Layout.cshtml 中声明部分并将其呈现在同一个文件中。标记没有出现,但是当我在_LayoutChild.cshtml 中声明部分时,一切正常。请参见下面的示例:
_Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
@RenderSection("A", false)
</head>
<body>
@section A{
<script>
alert("I'm in Layout!");
</script>
}
</body>
</html>
_LayoutChild.cshtml
@{
Layout = "_Layout";
}
@section A{
<script>
alert("I'm in LayoutChild!");
</script>
}
我知道在同一个文件中声明部分看起来很奇怪,但我想知道为什么它不起作用?
【问题讨论】:
-
请参阅我会将 _layoutchild.cshtml 视为部分内容。因此我不会使用
@RenderSection(),而是使用@Html.Partial()。我认为这会更好地解释。 weblogs.asp.net/scottgu/… 虽然老了,但它仍然是相关的 -
想一想,它永远不会像您期望的那样工作。
@RenderBody()应该在 _layout.cshtml 中。然后,一旦您进行渲染,例如Index(该部分将在实际的index与布局内)。 -
我认为 _LayoutChild.cshtml 用作视图文件。对吗?
标签: c# .net asp.net-mvc razor asp.net-core-mvc