'ViewComponents with children

Can I use ViewComponents in a page like this.

<vc:parent-component>
     <some random html>
</parent-component>

when I try this it renders out only parent component. In cshtml of parent-component I am looking for something like below

<h2>Parent component markup</h2>
@RenderChildren()??
<h2>Parent component markup end</h2> 

So result will be

<h2>Parent component markup</h2>
@RenderChildren()
<h2>Parent component markup end</h2>


Solution 1:[1]

You cannot use random html inside ViewComponent tag helper as you did. May be your are considering ViewComponent tag helper as like as html element. Actually its not html element, rather its a razor code.

According to the Invoking a view component as a Tag Helper documentation, Your ViewComponent tag helper should be like as follows

<vc:[view-component-name]
  parameter1="parameter1 value"
  parameter2="parameter2 value">
</vc:[view-component-name]>

Solution 2:[2]

You can use tag helpers when you need to pass children by having the following lines in your ProcessAsync function.

public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
    var childContent = await output.GetChildContentAsync();
    output.Content.SetHtmlContent(fullContent);
}

They do have limitations, because inside tag helpers you don't instantly have access to razor templates, but there is a way to overcome that:

Check this other answer:

How to render a Razor template inside a custom TagHelper in ASP.NET Core?

and this for additional context:

https://github.com/aspnet/Mvc/issues/5504

When you combine these two approaches you can actually have a full server rendered component without using Blazor if you don't need to.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TanvirArjel
Solution 2 Carlos Jimenez Bermudez