Search code examples
c#htmlpaginationparameter-passingblazor-server-side

How to pass the button value into an onclick event?


I have a for loop which will work out the number of buttons needed to display and then I wanted to pass in that i value to the method. However regardless of which button I press it is saying that i is 6 and is crashing. How do I get the specific buttons i value?

    @for (int i = 1; i < maxPage + 1; i++)
{
    <button value="@i" @onclick="@(e => dosomething(this.value))">@i</button>
}


@code {
    int maxPage = 5;
 
    private void dosomething(int val)
    {
        Console.WriteLine(val);
    }

   
}

Solution

  • @for(var i=0; i<5; i++) {
         var index = i;
         <button @onclick="@(e => click(index, 5 * index))">Button @i</button>
     } 
    
    
    @code {
         private void click(int a, int b) {
             Console.WriteLine(a + b);
         }
     }  
    

    the variable index holds the value of i for each button so that they don't change and each button has its own value