在 ASP.Net Core 中创建自定义 HTML 帮助程序 [英] Create Custom HTML Helper in ASP.Net Core
问题描述
我想创建自己的自定义 HTML Helper,就像在 ASP.NET MVC 中使用的那些一样,但我无法找到如何以正确的方式实现它们.
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.
我发现了如何创建自定义标签助手,但不是 HTML 助手.如何创建自己的自定义 HTML 助手?
I have found how to create custom Tag Helpers but not HTML Helpers. How do I create my own custom HTML Helpers?
推荐答案
对我来说,认为我的 HTML 助手无法正常工作,直到我发现扩展方法现在在 IHtmlHelper
不是 HtmlHelper
.
For me I thought my HTML helpers weren't working until I spotted that the extension method is now on IHtmlHelper
not HtmlHelper
.
所以对于 .net 核心:
public static IHtmlContent CheckboxListFor<TModel>(this IHtmlHelper<TModel> html,
Expression<Func<TModel, List<CheckboxListItem>>> expression) ...
代替 .net:
public static HtmlString CheckboxListFor<TModel>(this HtmlHelper<TModel> html,
Expression<Func<TModel, List<CheckboxListItem>>> expression) ...
我还将 .net 核心的返回类型更新为 IHtmlContent,因为使用类似 HtmlContentBuilder
的方法是一种更好的方式编写 HTML 内容并返回返回 IHtmlContent
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
这篇关于在 ASP.Net Core 中创建自定义 HTML 帮助程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!