Can a section define a body in an MVC layout file?

Is there a way in which I can define a section in an MVC Layout file then some content (also within the layout file) that will only get rendered when that section is rendered?

_Layout.cshtml

@RenderSection("mySection", required:false)
{
    //HTML content that will render on every page utilising this section
}

Additional Info: In my project every view inherits from a layout file which I define every HTML element common with each view but some pages have one additional common element that is not required to be displayed on each page but once it is defined the page contents need to be included within it

1 answer

  • answered 2018-07-11 06:05 Abs

    I think this can't be done and the closest is defining an almost identical layout file, but that is still ugly, therefore the below may be better:

    _Layout2.cshtml

    @RenderPage("_Layout")
    
    <div class="common-body-container">
        <div class="common-body-container-header">
            <div class="common-body-container-page-title">blah blah!</div>
        </div>
        <div class="common-body-container-contents">
            @RenderBody()
        </div>
    </div>
    

    This way I am not redifining an almost identical layout file and also not repeating the HTML tags forming the container on evey page.