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>
    <title>@ViewBag.Title -</title>
    <div class="container body-content">

        @*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>
            <p><b>Default content.</b></p>


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>




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>


You may also like...

Leave a Reply

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