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

标签 view migration asp.net-core extension-methods asp.net-core-mvc

我目前正在尝试将 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);
    }
}

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

最佳答案

而不是 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);
        }
    }
}

然后引用 Razor 页面中的类@using static Stackoverflow.SessionExtensions ,并这样称呼它:
@this.RenderSection("extra", @<span>This is the default!</span>))

一个 替代 方法是在 View 中执行此操作(我更喜欢这种方式,似乎更简单):
@if (IsSectionDefined("extra"))
{
    @RenderSection("extra", required: false)
}
else
{
    <span>This is the default!</span>
}

我希望这有帮助。

更新 1 (来自评论)

通过引用命名空间
@using Stackoverflow

您不必包含 static关键字,但是在调用它时,您必须引用命名空间中的实际类并传递 ' 这个 ' 进入函数。
@SectionExtensions.RenderSection(this, "extra", @<span>This is the default!</span>)

更新 2

razor 中有一个错误,不允许您调用模板委托(delegate) 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;
    }
}

然后是 Razor 页面:
section test {
    @this.RenderSection("extra", new HtmlString("<span>this is the default!</span>")); 
}

关于view - 如何在 MVC 6 中定义具有默认内容的部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34784314/

相关文章:

asp.net-core - 是否可以将 ffmpeg 命令的输出流式传输到具有 dot net core 的客户端?

sql-server-2008 - 截断 View 中的基础表

sharepoint - 将字段添加到 SPList 默认 View

django - 如何在 Python 模型迁移中生成基于函数的索引?

mysql - 从 MySQL 迁移到 SQLite3 有什么好的工具吗?

ruby-on-rails - Rails 中八卦搜索的迁移

c# - 拦截并更改应用程序生成的 sql 查询

ios - 仅更改 View 框架中的 1 个值

mysql - 字段列表中未知的列名 - MySQL

c# - 不同的最低级别日志 Serilog