I'm converting a project to ASP.NET Core. I need to migrate lots of reusable html helpers, but html helpers do not exist in Core.
Some are complex, some simple. Here's a extremely simple example:
@helper EditIcon()
{
<i class="glyphicon glyphicon-pencil"></i>
}
Note that this is only an example.
Point is writing a tag helper for that is gigantic overkill. Same for partials. Same for view components.
We're talking about a little snippet of Razor. What is my best option?
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
@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)
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" ); }
So, seems there are only three options:
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With