0

I am creating a pager component and faced a problem. I simplified the code to show the problem :

 @for (int i = 0; i < 10; i++)
        {
           
                <li @onclick="() =>UpdatePager(i)" class="waves-effect"><a>@(i+1)</a></li>
         
        }
@code{

    public void UpdatePager(int iCurPage)
    {
        Console.WriteLine(iCurPage);
    }

}
// when click on 1  console result is 10
// when click on 2  console result is 10
// ...
// when click on 10  console result is 10

My expectation is when I click any of lis the corresponding number(i) should be logged in the console but what is actually happen is for all of the lis the number 10 ( final value of i) is printed. What is the problem and how should I pass different values for each rendered elements?

nAviD
  • 2,784
  • 1
  • 33
  • 54
  • @Silvermind I missed that why it was closed ? – nAviD Feb 23 '21 at 17:22
  • 1
    It's a dup, and there isn't a Blazor specific solution. That said, you could use `foreach (int i in Enumerable.Range(0, 10)) {}` to fix the problem because the `foreach` loop already creates a shadow copy of `i`, unlike the `for` loop. – Kirk Woll Feb 23 '21 at 17:35
  • 2
    I've added a better dupe, and there are many more on SO, also for Blazor. – H H Feb 23 '21 at 18:34

0 Answers0