How to separate @RenderBody() into two parts

Viewed 1655

Im using ASP.NET Core 2.2. The problem that I have is I don't know where to use @RenderBody() in my _Layout page. This is representation of what I want to do: enter image description here

The green parts should come from _Layout and white parts coming from HomePage.cshtml. My HomePage consists of two parts a slider and a list of content below it.This is what I tried, but it doesn't meet my need because i can't put slider in it.

this is _Layout

<html>
   <body>
       <main>
       <header></header>
       <div class="left-col">
       <div class="content">@RenderBody()</div>
       <div class="right-col">
       <footer></footer>
    </main>
   </body>
</html>
1 Answers

You can define a section in the layout to render the desired content

HomePage.cshtml

@{
    ViewBag.Title = "Home Page";
}

@section Slider {

   <div>My HomePage slider</div>

}

<p>My HomePage content</p>

The layout would check to see if the section exists and render it if it does

_Layout.cshtml

<html>
   <body>
       <main>
       <header></header>
    @if (IsSectionDefined("Slider")) {
       <div class="homepage-slider">
         @RenderSection("Slider", required: false)
       </div>
    }
       <div class="left-col">
       <div class="content">@RenderBody()</div>
       <div class="right-col">
       <footer></footer>
    </main>
   </body>
</html>

You would obviously have to specify what ever styling needed to position the section where desired.

Reference Layout in ASP.NET Core: Sections

Related