Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render html renderfragment code in blazor

Tags:

blazor

I want to render the following HTML control dynamically into the .razor file

<input type="text" value="hola" />

I did the following :

<div>
    @att 
</div>

    [Parameter]
    public RenderFragment? att { get; set; }

    protected override async Task OnInitializedAsync()
        {
               att = @"<input type=""text"" value=""hola"" />";
        }

but I get an error converting string to RenderFragment type. How do I assign this? If I convert att - it to string the value is not HTML rendered, it displays the value as a code.

like image 685
Venkat Avatar asked Oct 26 '25 05:10

Venkat


2 Answers

You are getting the error because you are trying to set a delegate to a string. RenderFragment is not a string of html, it declared like this in the DotNetCore code:

public delegate void RenderFragment(RenderTreeBuilder builder);

Here's a version of your code that will compile and work, though why you want to do it that way?

<div>
    @att
</div>

@code {
    public RenderFragment? att { get; set; }

    protected override Task OnInitializedAsync()
    {
        att = (__builder) =>
        {
            <input type="text" value="hola" />
        };
        
        return Task.CompletedTask;
    }
}

You have declared att as a parameter so you should not be setting it in your code. Parameters should be treated as immutable outside the SetParametersAsync context.

This will work and I don't think breaks the rule:

    public RenderFragment? att { get; set; } = (__builder) =>
        {
            <input type="text" value="hola" />
        };
like image 176
MrC aka Shaun Curtis Avatar answered Oct 29 '25 09:10

MrC aka Shaun Curtis


The basic answer would be

RenderFragment attFallback => @<input type="text" value="hola" /> ;

RenderFragment att => attParam ?? attFallback; 

and then use @att in your markup.

but it depends on what you actually want to do with that <input>. When you @bind to something it gets more complicated.

like image 31
Henk Holterman Avatar answered Oct 29 '25 09:10

Henk Holterman