在 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 部分。我考虑过更改嵌套母版中部分的名称并在母版中检查该名称,但我们有许多嵌套母版,我觉得如果我们遵循这种模式,母版中将会出现不必要的爆炸。我怎样才能做到这一点?
最佳答案
您可以编写自定义扩展方法:
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")
关于asp.net-mvc - 如何使嵌套母版页 Razor 部分未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12496649/