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?

Rudi Visser
  • 21,350
  • 5
  • 71
  • 97
Okan Kocyigit
  • 13,203
  • 18
  • 70
  • 129

4 Answers4

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.

Rudi Visser
  • 21,350
  • 5
  • 71
  • 97
Raciel R.
  • 2,136
  • 20
  • 27
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>
Girish Gupta
  • 1,241
  • 13
  • 27
1

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

@RenderSection("SectionName", required: false)
Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36
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
chromigo
  • 1,134
  • 1
  • 15
  • 25