aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

Looping and passing arguments to a method

Open dlr1 opened this issue 8 years ago • 4 comments

I have the following code

@inherits MyCompBase

@for(var i=0; i< Counter;i++)
{
    <div onclick=@( x=>ItemClicked(i))>this is item @i</div>
}

using Microsoft.AspNetCore.Blazor.Components;
using System;

namespace WebApplication2.Shared
{
    public class MyCompBase : BlazorComponent
    {
        public int Counter { get; set; } = 4;
        public void ItemClicked(int value)
        {
            Console.WriteLine(value);
        }
    }
}

I expected it to write value "i" to be written to console when the div is clicked. it is always writing "4". what am I missing?

dlr1 avatar Apr 24 '18 13:04 dlr1

That's because i=4 at the end of the loop. i isn't 'rendered' like @i, it's just variable, and that the moment you click it's 4

floreseken avatar Apr 24 '18 13:04 floreseken

Thanks for answering, @floreseken !

I think to work around this issue you could use a new component instead of the div that capture the value of i as part of its state and then uses that state to write to the console.

danroth27 avatar Apr 24 '18 19:04 danroth27

Change your for loop to something like this:

@for(var i=0; i< Counter;i++)
{
    var local_i = i;
    <div onclick=@( x=>ItemClicked(local_i))>this is item @i</div>
}

Andrzej-W avatar Apr 24 '18 22:04 Andrzej-W

Thanks!. Much better solution

dlr1 avatar Apr 25 '18 00:04 dlr1