How to conditionally render sections in ASP.NET MVC ?

Conditionally render sections in ASP.NET MVC:

bool IsSectionDefined(string name): IsSectionDefined method can be used to check whether the section is defined in the view or not.

In the below example, in the Layout, IsSectionDefined  is used to check if the “CustomSection” section is defined in the view. If the “CustomSection” section is defined then it is rendered. And if “CustomSection” section is not defined in the view then default content that is present in the Layout will be displayed.

_Layout.cshtml content:

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title - TechCartNow.com</title>
</head>
<body>
    <div class="container body-content">
        @RenderBody()

        @*Returns a value that indicates whether the specified section is defined in the page.*@
        @if (IsSectionDefined(name: "CustomSection"))
        {
            // In layout pages, renders the content of a named section and specifies whether
            // the section is required.
            @RenderSection(name: "CustomSection")

            <p>Custom section content.</p>
        }
        else
        {
            <p><b>Default content.</b></p>
        }

    </div>
</body>
</html>

Index.cshtml content with CustomSection :

CustomSection content will be displayed.

@{
    ViewBag.Title = "Index Page with CustomSection";
}

<p>Index page content.</p>

@section CustomSection {
    <p><b>Custom view content.</b></p>
}

Output:

ASP.NET MVC RAZOR SECTION

 

About.cshtml content without CustomSection :

Default content specified in the Layout will be displayed.

@{
    ViewBag.Title = "About Us Page without CustomSection";
}

<p>About us page content.</p>

Output:

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *