Search code examples
asp.net-coreasp.net-core-mvc

Create Custom HTML Helper in ASP.Net Core


I want to create my own custom HTML Helper like the ones used in ASP.NET MVC, but I haven't been able to find how to implement them in the correct way.

I have found how to create custom Tag Helpers but not HTML Helpers. How do I create my own custom HTML Helpers?


Solution

  • For me I thought my HTML helpers weren't working until I spotted that the extension method is now on IHtmlHelper not HtmlHelper.

    So for .net core:

    public static IHtmlContent CheckboxListFor<TModel>(this IHtmlHelper<TModel> html,
                Expression<Func<TModel, List<CheckboxListItem>>> expression) ...
    

    Instead of for .net:

    public static HtmlString CheckboxListFor<TModel>(this HtmlHelper<TModel> html,
                Expression<Func<TModel, List<CheckboxListItem>>> expression) ...
    

    EDIT: I've also updated the return type for .net core to be IHtmlContent as using something like HtmlContentBuilder is a nicer way to compose HTML content and returning that returns IHtmlContent