Migrate html helpers to ASP.NET Core

I have successfully converted ASP.NET MVC Razor Helpers to Function Directives in .NET CORE 3.1 as an example shown below:

E.g. ASP.NET MVC 5 @helper syntax:

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


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

Equivalent ASP.NET CORE 3.1 @functions directive syntax:

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

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

Razor Function Directives


So, seems there are only three options:

  • tag helpers
  • partials
  • view components

So no simple way to migrate Razor snippets, without jumping through hoops.


EDIT

So looks like html helpers are available after all. They just haven't been properly documented!


Personally I think this approach is cleaner for small in-page snippets:

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>
    }
}

and place it like this:

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

@helper directive is removed, but if you may consider using Func<dynamic, IHtmlContent> you are migrating a legacy code. Here is an example:

@{
    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>;
}

And use it just like old helper methods:

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