将 html 个助手迁移到 ASP.NET 个核心

Migrate html helpers to ASP.NET Core

我正在将项目转换为 ASP.NET 核心。我需要迁移大量可重用的 html 助手,但 html 助手在 Core 中不存在。

有些复杂,有些简单。这是一个非常简单的例子:

@helper EditIcon()
{
    <i class="glyphicon glyphicon-pencil"></i>
}

请注意,这只是一个示例。

Point 正在为此编写一个标记助手,这是巨大的矫枉过正。 与部分相同。视图组件也一样。

我们正在谈论 Razor 的一小段。我最好的选择是什么?

所以,似乎只有三个选项:

所以没有简单的方法来迁移 Razor 代码片段,而不跳过箍。


编辑

所以 looks like html helpers are available 毕竟。它们只是没有被正确记录!

@helper 指令已删除,但如果您可以考虑使用 Func<dynamic, IHtmlContent>,那么您正在迁移遗留代码。这是一个例子:

@{
    Func<dynamic, IHtmlContent> BrowserInfo(string btitle, string href, string imgfilename) =>
        @<div style="text-align: center">
            <a href="@href">
                <img src="~/content/images/browsers/@imgfilename" alt="@btitle"/>@btitle</a>
        </div>;
}

并像使用旧的辅助方法一样使用它:

@BrowserInfo("Google Chrome", "http://www.google.com/chrome/", "browser_chrome.gif")(null)

我个人认为这种方法对于页面内的小片段更清晰:

https://www.mikesdotnetting.com/article/344/what-happened-to-helpers-in-asp-net-core

[...] One of those things is a more formal replacement for the Razor helper. You can now include HTML markup in the body of a method declared in a code block as a local method as previously, or in an @functions block. The method should return void, or Task if it requires asynchronous processing. Here is how the list helper is written in ASP.NET Core 3:

@{
    void Template(string[] listItems, string style) 
    {
        <ul>
        foreach (var listItem in listItems)
        {
            <li class="@style">@listItem</li>
        }
        </ul>
    }
}

然后这样放置:

@{ Template(new[] { "A","B","C" },  "pretty" ); }

我已经成功地将 ASP.NET MVC Razor Helpers 转换为 .NET CORE 3.1 中的函数指令,如下所示:

例如 ASP.NET MVC 5 @helper 语法:

<div>
       @RenderHello();
</div>


@helper RenderHello() {
        <strong>Hello</strong>
}

等效于 ASP.NET CORE 3.1 @functions 指令语法:

<div>
    <text>
    @{
        RenderHello();
    }
    </text>
</div>

@functions {
    private void RenderHello()
    {
        <strong>Hello</strong>
    }
}

Razor Function Directives