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.
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" />
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With