21

我有三个简单的布局,

_Layout.cshtml(这是基本布局)

@RenderSection("something", required: false)
@RenderBody()

_Main.cshtml

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section something {
   Hey I'm actually on the _Main layout.
}

索引.cshtml

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

当我尝试在操作中呈现索引视图时,出现此错误,

尚未为布局页面“~/Views/Shared/_Main.cshtml”调用“RenderBody”方法。

但是等等,_Main.cshtml有一个父布局已经有一个RenderBody(). 所以我错了,我必须调用RenderBody()每个子布局吗?

4

4 回答 4

25

Yes, RenderBody should be included on every layout page, regardless the nesting.

@RenderBody works as a placeholder for the engine to know where to drop the content of the view using the layout page.

于 2013-08-19T21:21:59.660 回答
7

此代码应该可以正常工作:

_Layout.cshtml

@RenderSection("something", required: false)
@RenderBody()

_Main.cshtml

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
 }
@section something {
   Hey I'm actually on the _Main layout.
}

索引.cshtml

@{
    Layout = "~/Views/Shared/_Main.cshtml";
 }
<div id="Index Content Here">
 @RenderBody()
 </div>

index.cshtml 应按以下方式呈现:

<head>
Hey I'm actually on the _Main layout.   
</head>
 <div id="Index Content Here">
</div>
</div>
于 2014-09-23T04:13:44.727 回答
1

部分可以通过渲染它们成为可选的required: false

@RenderSection("SectionName", required: false)
于 2016-04-05T15:38:52.387 回答
0

尝试在最后一个视图中包含部分。

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

@section something {
    content
}

更新:好的,我想说你还需要在 _Main 布局中编写 @RenderSection

@section something {
    Hey I'm actually on the _Main layout.
    @RenderSection("something", required:false)
}
enter code here
于 2016-04-05T14:01:32.537 回答