In a view component invoked as a tag helper, how c

2019-07-26 07:48发布

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条回答
贪生不怕死
2楼-- · 2019-07-26 08:41

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."

查看更多
登录 后发表回答