Search code examples
c#asp.net-core-mvc

Check RenderSectionAsync in _Layout is empty or not (ASP.NET Core MVC)


This is my _Layout.cshtml:

@await RenderSectionAsync("SpecialHeader", required: false)

Some views have this and some don't:

@section SpecialHeader
{
    // something
}

So far so good.

Now how can I check whether RenderSectionAsync (in _Layout.cshtml) is null (empty) or not?

I want something like this:

if (RenderSectionAsync == null)   // this is in my mind
{
    // Public Header
}
else
{
    @await RenderSectionAsync("SpecialHeader", required: false)
}

Solution

  • You can use RazorPage.IsSectionDefined(string) method to check if the specified section is defined in the content page.

    In the _Layout.cshtml page, add the following code:

    @if (IsSectionDefined("SpecialFooter"))
    {
        @await RenderSectionAsync("SpecialFooter", required: false)
    }
    else{
        <div>Default Content</div>
        @* IgnoreSection("SpecialFooter"); *@
    }
    

    Then in the content page:

    Index page: define the section.

    @section SpecialFooter {
        <div>custom footer</div>
    }
    

    Privacy page: without define the section.

    The result as below:

    Index page:

    enter image description here

    Privacy page:

    enter image description here