在标签助手中,我们可以访问标签内部的 HTML。
<!-- Index.cshtml -->
<my-first>
This is the original Inner HTML from the *.cshtml file.
</my-first>
// MyFirstTagHelper.cs > ProcessAsync
var childContent = await output.GetChildContentAsync();
var innerHtml = childContent.GetContent();
Run Code Online (Sandbox Code Playgroud)
如果我们调用视图组件作为标签助手,我们如何访问内部 HTML?
<vc:my-first>
This is the original Inner HTML from the *.cshtml file.
</vc:my-first>
// MyFirstViewComponent.cs > InvokeAsync()
var innerHtml = DoMagic();
Run Code Online (Sandbox Code Playgroud)
一些进一步的想法:
我很欣赏我们可以通过 HTML 属性将任意内容传递给视图组件。但是,在文本量非常大的情况下,这可能变得不切实际,在这种情况下,内部 HTML 会更具可读性并且具有更好的工具支持。
有些人可能还会说,“那么为什么不直接使用标签助手呢?” 好吧,我们想要将视图与标签助手关联起来,而标签助手不支持视图;相反,标签助手要求我们以编程方式构建所有 HTML。
所以我们陷入了困境。一方面,我们想要一个标签助手,但它们不支持视图;另一方面,我们可以使用视图组件作为标签助手,但视图组件可能不允许我们访问内部 HTML。
asp.net-core-mvc tag-helpers asp.net-core asp.net-core-mvc-2.0 asp.net-core-viewcomponent