How can I write Blazor HTML code within a function inside of the @code
block?
Consider the following code:
@page "/Test"
@if (option == 1)
{
drawSomething("Something");
}
else
{
drawSomething("Something else");
}
@code {
int option;
void drawSomething(string message)
{
<p>message</p>
}
}
It does not produce any errors until I try to build, then it gives me the following error:
Error CS0103 The name '__builder' does not exist in the current context
On the lines in (Test.razor.g.cs
):
__builder.AddContent(0, " ");
__builder.AddMarkupContent(1, "<p>message</p>\r\n");
It seems very limited if this means Blazor HTML code can only be written in the first part of the file and not inside functions or classes.
I'm using the latest version as of writing version (3.0.100-preview9-014004
) of blazor.
Note: The output in the given example is highly simplified, and I would like to know if and how I am able to write code from within a function and not solve the output above in a better way.
Update, you can now use:
@GreetPerson("John")
@code {
RenderFragment GreetPerson(string name)
{
return @<p>Hello <em>@name</em></p>;
}
}
Old answer:
This was announced as a feature for Preview6 but it didn't work as advertised then, and some details seem to have changed later. There is a comment from Cosmin Sontu at the bottom of that page that points the right way:
@using Microsoft.AspNetCore.Components.Rendering
@*tested with preview 9*@
@{ GreetPerson(__builder, "John"); }
@code {
void GreetPerson(RenderTreeBuilder __builder, string name)
{
<p>Hello, <em>@name!</em></p>
}
}
The name __builder
cannot be changed. That is a double underscore.
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