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?
RenderBody() renders all the content of the child view which is not wrapped in the named section. RenderSection() renders only a part of the child view which is wrapped under the named section. Multiple RenderBody() methods are NOT allowed in a single layout view.
A layout page can only contain one RenderBody method, but can have multiple sections. To create a section you use the RenderSection method. The difference between RenderSection and RenderPage is RenderPage reads the content from a file, whereas RenderSection runs code blocks you define in your content pages.
RenderBody() is called to render the content of a child view. Any content on said view that is not in a @section declaration will be rendered by RenderBody() . Using the Layout view above, that means that all content in a child view will be rendered inside the <div class="container body-content"> .
We can also create multiple _ViewStart. cshtml pages. The file execution is dependent upon the location of the file within the folder hierarchy and the view being rendered. The MVC Runtime will first execute the code of the _ViewStart.
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.
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>
<head> Hey I'm actually on the _Main layout. </head> <div id="Index Content Here"> </div> </div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With