Search code examples
asp.netasp.net-mvcrazorasp.net-mvc-5razorengine

Detect if a section is available before @RenderSection


I have a piece of code which I would like to render conditionally, if a section exists...

<aside>
    <h1>Navigation</h1>
    @RenderSection("navigation", false)
</aside>

But I only want it to render if the section exists on the page; something like this

<aside>
    @if(SectionAvailable("navigation")) {
        <h1>Navigation</h1>
        @RenderSection("navigation", false)
    }
</aside>

Is there any way to do this?


Solution

  • You can detect if a section is defined like so:

    @if(IsSectionDefined("navigation"))
    {    
        <h1>Navigation</h1>
        @RenderSection("navigation", false)
    }
    

    Source