Search code examples
asp.netasp.net-mvcasp.net-mvc-4razorrazor-2

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


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?


Solution

  • 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.