ASP.NET MVC - Render section conditionally in Layout

igorGIS picture igorGIS · Oct 4, 2013 · Viewed 9k times · Source

i have following code in my _Layout.cshtml:

@if (SiteConfig.Instance.HasCustomMarkup)
{
     @RenderSection("bodyPart1", false)
     @RenderBody()
     @RenderSection("bodyPart2", false)
}
else
{
    <div id="mainContainer">
        @RenderBody()
    </div>        
}

So i try to render sections only on some condition. But it is not work and i have an exception:

The following sections have been defined but have not been rendered for the layout page ...

Is there any workaround in mvc for this purposes? thanks!

Answer

Max picture Max · Oct 4, 2013

Simply check whether or not section exists, i.e.:

@if (IsSectionDefined("bodyPart1"))
{
    @RenderSection("bodyPart1")
}