Home > Blockchain >  Can child content be added to MarkupString with RenderFragment?
Can child content be added to MarkupString with RenderFragment?

Time:05-30

I have code like this;

@((MarkupString)$"<{item.Tagname}> {ChildContent} </{item.TagName}>")

ChildContent in the middle is a RenderFragment object, but it outputs as follows;

"Microsoft.AspNetCore.Components.RenderFragment"

Is there a way to make it work normally this way?

CodePudding user response:

I'm guessing you're trying to do something like this.

The example uses a RenderTreeBuilder to construct the markup. It's the eqivalent to writing assembler for components, but as the markup gets complex it's the only sensible way!

If you use this method one word of advice: the sequence numbers need to be coded manually, do not use an iterator.

@this.content

@code {
    [Parameter] public RenderFragment? ChildContent { get; set; }

    [Parameter] public string TagName { get; set; } = "div";

    private RenderFragment content => builder =>
    {
        builder.OpenElement(0, TagName);
        builder.AddContent(1, ChildContent);
        builder.CloseComponent();
    };
}

Or as a complete component:

public class ComponentClass : ComponentBase
{
    [Parameter] public RenderFragment? ChildContent { get; set; }

    [Parameter] public string TagName { get; set; } = "div";

    protected override void BuildRenderTree(RenderTreeBuilder builder)
    {
        builder.OpenElement(0, TagName);
        builder.AddContent(1, ChildContent);
        builder.CloseComponent();
    }
}
  • Related