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>
}
You can use a lambda expression to pass multiple arguments to an onclick event.
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.
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.
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.
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()
.
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