Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Render section conditionally in Layout

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!

like image 822
igorGIS Avatar asked Oct 04 '13 10:10

igorGIS


People also ask

What are layouts and sections in MVC?

The Layouts and sections in ASP.NET MVC core help us to maintain a consistent look across all the pages or views of our application. In this tutorial, we will learn how to create a Layout page, which is shared between the views. We will use the Renderbody to render the view.

Can We render layouts based on a condition in MVC?

Using the method described above we can render layouts based on a condition in ASP.NET MVC. Microsoft Consultant. Office 365 / SharePoint / PowerApps / Power Automate / Azure. #SharePoint Architect

How to define @rendersection in ASP NET MVC?

Two steps are there to define @RenderSection in ASP.NET MVC. A. Specify a @RenderSection Area in Layout Page. <!-- End of Content Body --> <!-- Footer --> B. Use this specified section to inject content from child page. Hello CompShop Application.

Can we change layout page at runtime in MVC?

This is very similar to Master Page in ASP.NET application. Layout page is located within a shared folder inside the view folder. The Layout page helps us to maintain a consistent look and feel within an application. Can we change the layout page at runtime or based on the condition in our MVC application? This is possible with a MVC application.


1 Answers

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

@if (IsSectionDefined("bodyPart1"))
{
    @RenderSection("bodyPart1")
}
like image 112
Max Avatar answered Sep 22 '22 13:09

Max