Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

blazor return RenderFragment '__builder' does not exist in the current context

I'm trying to return a RenderFragment from a component private method, but I'm getting the compilation error:

'__builder' does not exist in the current context

here's the minimum code that shows the problem:

<div>
    @RenderButton(1)
</div>

@code {
    private RenderFragment RenderButton(int number)
    {        
        return builder =>
        {
            <button type="button">@number</button>
        };
    }
}

it appears to me that this might not be possible/allowed, if not, is there any way to avoid having to write the same render code?, let's say that I need to use this RenderButton method in multiple loops, and if else blocks

edit: the only solution I can think of now is to create a component for each of these RenderFragment methods

like image 815
buga Avatar asked Jul 18 '26 17:07

buga


1 Answers

Your code seems to be for an earlier version of Blazor.

Blazor now has a more elegant notation, using templated delegates:

private RenderFragment RenderButton(int number) 
{
     return @<button type="button">@number</button>;
}

The explanation for your error is that __builder is a fixed name, used by the transpiler. You could also fix your code like this:

// not recommended
private RenderFragment RenderButton(int number)
{        
    return __builder =>
    {
        <button type="button">@number</button>
    };
}

The razor compiler is able to do a smart switch on the @ and ; and inserts the __builder => ... part behind the curtains.

like image 65
Henk Holterman Avatar answered Jul 21 '26 07:07

Henk Holterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!