Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

blazor variable argument passing to onclick function [duplicate]

I want to pass the int i into the button onclick function for each list item. I expected the "clickItem" function will receive 0..2 for correspondig list item. But it come out that it always receive 3 as argument. It seems that the variable i in the clickItem(i) is not evaluated at the time of render of the for loop. I have tried changing it to "clickItem(@i)" but it is still the same. What should I do? (I am using blazor server side, .net core 3 preview 5)

        @for (int i = 0; i < 3; i++)
        {
            <li> item @i <button onclick=@(() => clickItem(i))>Click</button> </li>
        }

enter image description here

like image 971
Raymond Wong Avatar asked Jun 03 '19 10:06

Raymond Wong


People also ask

How do you pass arguments to onclick functions in Blazor?

You can use a lambda expression to pass multiple arguments to an onclick event.

How do you trigger click event in Blazor?

Blazor does not have support to manipulate DOM elements directly, but we can still achieve it by using JavaScript interop. By creating a reference to an element, we can send it as a parameter to the JavaScript method via interop.

How do you pass parameters in Blazor?

By using Blazor route parameters, you can pass values from one page to another page. Use NavigationManager to pass a value and route the parameter to another page. Follow this example to achieve passing values from one page to another. Get the passed Page1 parameter value in Page2.

How do I redirect in Blazor?

You can redirect to a page in Blazor using the Navigation Manager's NavigateTo method. In the following code snippet, it will redirect to the home page when this page gets loaded. Similarly, you can call NavigateTo() method from NavigationManager class anywhere to redirect to another page.


1 Answers

This is a classic, but slightly new in the context of Blazor.

You need to make a copy because otherwise the lambda 'captures' the loop variable. Capturing the copy is OK.

@for (int i = 0; i < 3; i++)
{
    int copy = i;
    <li> item @i <button onclick=@(() => clickItem(copy))>Click</button> </li>
}

Note that this is an issue with for() loops but not with foreach().

like image 155
Henk Holterman Avatar answered Sep 16 '22 15:09

Henk Holterman