2

在 Razor 中,我有一个母版页,其中定义了一个部分,如果没有值,则显示一些默认值:

<html>
<head><title>Title</title></head>
<body>
    @if (IsSectionDefined("optionalSection"))
    {
        @RenderSection("optionalSection", required: false)
    }
    else
    {
        <div>Some default content</div>
    }
</body>
</html>

我还有一个嵌套的母版页,它创建了一个通过部分定义:

@section optionalSection {
    @RenderSection("optionalSection", required: false)
}

我遇到的问题是,当我使用这个嵌套的母版页时,母版页认为该部分总是被定义的。这将永远不会显示 else 部分。我考虑过在嵌套母版中更改部分的名称并在母版中检查它,但是我们有许多嵌套母版,我觉得如果我们遵循这种模式,母版中会出现不必要的爆炸。我怎样才能使这项工作?

4

1 回答 1

2

您可以编写自定义扩展方法:

public static class SectionExtensions
{
    public static HelperResult RedefineSection(
        this WebPageBase page,
        string sectionName
    )
    {
        if (page.IsSectionDefined(sectionName))
        {
            page.DefineSection(
                sectionName,
                () => page.Write(page.RenderSection(sectionName))
            );
        }
        return new HelperResult(_ => { });
    }
}

然后在您的嵌套布局中调用此扩展方法来重新定义该部分:

@this.RedefineSection("optionalSection")
于 2012-09-19T14:55:23.270 回答