liveBook · Manning

RenderBody

As explained in ASP.NET Core in Action, 3e

RenderBody is the Razor layout method that renders the body content supplied by a child view at its invocation location.

RenderBody is the Razor layout method that marks where a child view’s body content appears. A layout typically places it inside shared HTML such as the document body, alongside common headers, footers, styles, and scripts. section 17.4.1

A basic layout

In _Layout.cshtml, @RenderBody() supplies the page-specific markup: <html> <head> <title>@ViewData["Title"]</title> <link rel="stylesheet" href="~/css/site.css" /> </head> <body> @RenderBody() </body> </html> A view can select this layout with Layout = "_Layout". Its heading and paragraph then appear at the RenderBody location, while ViewData can provide the page title. section 17.4.1

Use RenderBody with these layout rules:

  • Call RenderBody in every layout that renders a child view body; otherwise Razor throws an InvalidOperationException unless the body is explicitly ignored. section 17.4.2
  • Use sections when one body location is too restrictive, such as a sidebar or optional scripts area. section 17.4.1 section 17.4.2
  • Nest layouts when different groups of views share additional structure beyond the base layout. section 17.4.2
Listing 17.7 A basic _Layout.cshtml file calling RenderBody
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewData["Title"]</title>                 #1
    <link rel="stylesheet" href="~/css/site.css" />   #2
</head>
<body>
    @RenderBody()                                     #3
</body>
</html>
#1 ViewData is the standard mechanism for passing data to a layout from a view.
#2 Elements common to every page, such as your CSS, are typically found in the layout.
#3 Tells the templating engine where to insert the child view’s content

Inspect the complete _Layout.cshtml example showing shared document markup, ViewData, a stylesheet, and the RenderBody call. section 17.4.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains the insertion mechanic, layout requirement, rendered result, and alternatives through sections and nested layouts.
Examples
Uses a basic _Layout.cshtml, a home view, rendered HTML, and a two-column layout with a sidebar section.
What it assumes
Assumes familiarity with Razor views and layouts while demonstrating layout selection and body composition.
What you can do after
Apply it via Razor layouts to combine shared page structure with view-specific content.
How it connects
Connects layouts with child views, ViewData, sections, nested layouts, and partial views.

Also explained in

Compare how 2 books explain RenderBody →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.