Search code examples
c#razorblazorblazor-webassembly

c# blazor Can't pass "i" into function, any other way?


I want to pass "i" as a parameter on @onclick="()=>ButtonToggle(i)", that seems to not work, is there an intended way to do it? Like store the "i" as element id and then referencing the id in "ButtonToggle(ElementIdReference)"?

Note: I know it can be done with components, I'm trying to keep it as simple as possible that's why im not using them in this case.

@for (int i = 0; i < 10; i++)
    {
        <button  style='@(ChosenKanas[i] == true ? "background-color: hotpink;" : "")' @onclick="()=>ButtonToggle(i)"  >@MainHiraganas[0,0]/@MainHiraganas[i,0]</button>
        
    }

Solution

  • It's called "closing over the loop variable".

    @for (int i = 0; i < 10; i++)
    {
        int iCopy = i; 
        <button  style='@(ChosenKanas[i] == true ? "background-color: hotpink;" : "")' 
           @onclick="()=>ButtonToggle(iCopy)">
           @MainHiraganas[0,0]/@MainHiraganas[i,0]</button>        
    }
    

    the iCopy is needed on the right side of the =>