RenderBody() and RenderSection() must be on every child layout?
Asked Answered
P

4

21

I have three simple layout,

_Layout.cshtml (this is the base layout)

@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";
}

When I try to render Index view in an action, I got this error,

The "RenderBody" method has not been called for layout page "~/Views/Shared/_Main.cshtml".

But wait, _Main.cshtml has a parent layout which already has a RenderBody(). So am I wrong, must I call RenderBody() for every child layout?

Photostat answered 19/8, 2013 at 21:15 Comment(5)
@asymptoticFault, no it's just a mistake.Photostat
I'm not sure you can use nested layouts like that.Fret
Yes, you can nest layouts. Usually you can either have different inner layout pages or conditionally display content in your view.Achromat
Ah ok, hadn't tried that myself.Fret
Because you are using _Main.cshtml as the layout page, you'll need to add RenderBody()Amphiboly
A
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.

Achromat answered 19/8, 2013 at 21:21 Comment(0)
M
7

This code should work properly:

_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 should be rendered as per below:

<head>
Hey I'm actually on the _Main layout.   
</head>
 <div id="Index Content Here">
</div>
</div>
Mohsen answered 23/9, 2014 at 4:13 Comment(0)
M
1

Sections can be made optional by rendering them with required: false

@RenderSection("SectionName", required: false)
Mousy answered 5/4, 2016 at 15:38 Comment(0)
P
0

Try to include section in last view.

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

@section something {
    content
}

UPDATE: Okay, I fogot to say that you need also write @RenderSection in _Main layout

@section something {
    Hey I'm actually on the _Main layout.
    @RenderSection("something", required:false)
}
enter code here
Perspicacity answered 5/4, 2016 at 14:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.