Skip to content
Ivan Balan edited this page Aug 7, 2016 · 1 revision

Example

Layout:

<div id="header">
    <!--Some content here -->
</div>

<div id="sidebar">
    @RenderSection("sidebar", required: false)
</div>

<div id="content">
    @RenderBody()
</div>

The first parameter to the "RenderSection()" method specifies the name of the section we want to render at that location in the layout template. The second parameter is optional, and allows us to define whether the section we are rendering is required or not. If a section is "required", then Razor will throw an error at runtime if that section is not implemented within a view template that is based on the layout file (which can make it easier to track down content errors). If a section is not required, then its presence within a view template is optional, and the above RenderSection() code will render nothing at runtime if it isn’t defined.

View:

@model MyTestViewModel

@{
    Layout = "_Layout.cshtml";
}

<div id="content">
    <!--Some content here-->
</div>

@section sidebar {
    <p>This will be rendered inside Layout</p>
}

We could have put our SideBar @section declaration anywhere within the view template. I think it looks cleaner when defined at the top or bottom of the file – but that is simply personal preference. You can include any content or code you want within @section declarations.

Clone this wiki locally