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

1

7

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

Hildredhildreth answered 24/11, 2021 at 12:36 Comment(0)
B
14

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.

Brigand answered 24/11, 2021 at 13:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.