Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor does not refresh UI when parameter is passed with onclick function

In Blazor ServerSide Asp.net core 3.0 Preview 6 the UI does not refresh. I have altered the counter.razor as an example. If you click the buttons "Set counter to ..." the counter is not refreshed. When you click the "Click me" button (is without a parameter) the UI is refreshed and 1 is added to the counter previous clicked.

The buttons seems to work, but the UI is not refreshed.

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>
<br />

<p>
    <button class="btn btn-primary" @onclick="@IncrementCount">Click me</button>
</p>

    @for (int i = 0; i < 5; i++)
    {
        var a = i;
        <p><button class="btn btn-primary" onclick="@(() => test(a))">Set counter to @a</button></p>
    }

    @functions {
        int currentCount = 0;

        protected void IncrementCount()
        {
            currentCount++;
        }

        void test(int i)
        {
            currentCount = i;
        }
    }

Any suggestions how to fix this is or is it a bug in Blazor?

like image 726
Marco Duindam Avatar asked Mar 16 '26 16:03

Marco Duindam


1 Answers

The @functions { } syntax suggests this was started with Preview5, but in Preview6 (current) the syntax for eventhandlers has changed:

Specifying event handlers in Blazor now uses the new directive attribute syntax instead of the normal HTML syntax. The syntax is similar to the HTML syntax, but now with a leading @ character. This makes C# event handlers distinct from JS event handlers.

  <button @onclick="@Clicked">Click me!</button>

When specifying a delegate for C# event handler the @ prefix is currently still required on the attribute value, but we expect to remove this requirement in a future update.

So you need @onclick="@(() => test(a))

like image 92
Henk Holterman Avatar answered Mar 18 '26 05:03

Henk Holterman