In a view component invoked as a tag helper, how can we access the inner HTML?

China☆狼群 提交于 2019-12-24 08:57:22

问题


In tag helpers, we can access the tags inner 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();

If we invoke a view component as a tag helper, how can we access the inner HTML?

<vc:my-first>
    This is the original Inner HTML from the *.cshtml file.
</vc:my-first>

// MyFirstViewComponent.cs > InvokeAsync()
var innerHtml = DoMagic();

A few further thoughts:

I appreciate that we can pass arbitrary content to a view component via HTML attributes. That can become impractical, though, in the case of very large amounts of text, in which case inner HTML would be more readable and have better tooling support.

Some might also say, "Why not just use a tag helper, then?" Well, we want to associate a view with the tag helper, and tag helpers do not support views; instead, tag helpers require us to build all the HTML programmatically.

So we're stuck in a bit of bind. On the one hand, we want a tag helper, but they don't support views; on the other hand, we can use a view component as a tag helper, but view components might not let us access the inner HTML.


回答1:


Sorry, but the answer is "Just use a tag helper"

See the following issue: https://github.com/aspnet/Mvc/issues/5465

Being able to invoke a ViewComponent from a tag helper is just a different way to call it instead of using @Component.Invoke().

I can see where this is misleading, and I do recall seeing in the ASP.NET Core 2.1 tutorials a statement to the effect of "View Components are like Tag Helpers, but more powerful."



来源:https://stackoverflow.com/questions/50889261/in-a-view-component-invoked-as-a-tag-helper-how-can-we-access-the-inner-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!