如何在MVC 6中定义具有默认内容的部分?

Coo*_*eze 9 migration extension-methods view asp.net-core-mvc asp.net-core

我目前正在尝试将ASP.net MVC 5项目迁移到MVC 6.

我将如何迁移以下代码:

public static class SectionExtensions
{
    public static HelperResult RenderSection(this WebPageBase webPage, [RazorSection] string name, Func<dynamic, HelperResult> defaultContents)
    {
        return webPage.IsSectionDefined(name) ? webPage.RenderSection(name) : defaultContents(null);
    }
}
Run Code Online (Sandbox Code Playgroud)

[RazorSection]是JetBrains.Annotations程序集的一部分.

Nic*_*eer 9

而不是WebPageBase我用RazorPageMicrosoft.AspNet.Mvc.Razor

namespace Stackoverflow
{
    public static class SectionExtensions
    {
        public static IHtmlContent RenderSection(this RazorPage page, [RazorSection] string name, Func<dynamic, IHtmlContent> defaultContents)
        {
            return page.IsSectionDefined(name) ? page.RenderSection(name) : defaultContents(null);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在剃刀页面中引用该类@using static Stackoverflow.SessionExtensions,并像这样调用它:

@this.RenderSection("extra", @<span>This is the default!</span>))
Run Code Online (Sandbox Code Playgroud)

一种方法是在视图中执行此操作(我更喜欢这种方式,看起来更简单):

@if (IsSectionDefined("extra"))
{
    @RenderSection("extra", required: false)
}
else
{
    <span>This is the default!</span>
}
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助.

更新1(来自评论)

通过引用命名空间

@using Stackoverflow
Run Code Online (Sandbox Code Playgroud)

您不必包含static关键字,但在调用它时,您必须引用命名空间中的实际类,并将" this " 传递给函数.

@SectionExtensions.RenderSection(this, "extra", @<span>This is the default!</span>)
Run Code Online (Sandbox Code Playgroud)

更新2

剃刀中有一个错误,它不允许您Func <dynamic, object> e = @<span>@item</span>;在一个部分内调用模板代理.请参阅https://github.com/aspnet/Razor/issues/672

目前的解决方法:

public static class SectionExtensions
{
    public static IHtmlContent RenderSection(this RazorPage page, [RazorSection] string name, IHtmlContent defaultContents)
    {
        return page.IsSectionDefined(name) ? page.RenderSection(name) : defaultContents;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后是剃须刀页面:

section test {
    @this.RenderSection("extra", new HtmlString("<span>this is the default!</span>")); 
}
Run Code Online (Sandbox Code Playgroud)