检查_Layout中的RenderSectionAsync是否为空(ASP.NET Core MVC)

问题描述 投票:0回答:1

这是我的

_Layout.cshtml
:

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

有些观点有这个,有些则没有:

@section SpecialHeader
{
    // something
}

到目前为止一切顺利。

现在如何检查

RenderSectionAsync
(在
_Layout.cshtml
中)是否为null(空)?

我想要这样的东西:

if (RenderSectionAsync == null)   // this is in my mind
{
    // Public Header
}
else
{
    @await RenderSectionAsync("SpecialHeader", required: false)
}
c# asp.net-core-mvc
1个回答
0
投票

您可以使用

RazorPage.IsSectionDefined(string)
方法来检查指定的部分是否在内容页面中定义。

在_Layout.cshtml页面中,添加以下代码:

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

然后在内容页面:

索引页:定义部分。

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

隐私页面:无定义部分。

结果如下:

索引页:

隐私页面:

© www.soinside.com 2019 - 2024. All rights reserved.