RenderBody()和RenderSection()必须在每个子布局上?

时间:2013-08-19 21:15:41

标签: asp.net asp.net-mvc asp.net-mvc-4 razor razor-2

我有三个简单的布局,

_Layout.cshtml (这是基本布局)

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

_Main.cshtml

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

Index.cshtml

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

当我尝试在动作中渲染索引视图时,我收到此错误,

  

" RenderBody"尚未为布局页面调用方法   "〜/查看/共享/ _Main.cshtml"

但等等,_Main.cshtml的父布局已经有RenderBody()。 我错了,我必须为每个子布局调用RenderBody()吗?

4 个答案:

答案 0 :(得分:23)

是的,无论嵌套如何,RenderBody都应该包含在每个布局页面中。

@RenderBody作为引擎的占位符,知道使用布局页面删除视图内容的位置。

答案 1 :(得分: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.
}

<强> Index.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>

答案 2 :(得分:1)

通过使用required: false

呈现部分,可以使部分成为可选部分
@RenderSection("SectionName", required: false)

答案 3 :(得分: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