How do I call a function or method from the generated DOM button?

Platform: Blazor| Category: Components

Generally, we are using lambda expressions to create DOM elements dynamically like in the following code snippet.

<div class="buttons">
     @for (int i = 0; i < 5; i++)
     {
         <button type="button" class="btn btn-primary" onclick="@((e) => ButtonClicked(i))">Button @i</button>
     }
 </div> 

The lambda expressions access variables instead of their values. The button click is triggered with the number 5.

You have to include local variables while rendering the button element to properly get the index value of the clicked button element.

 

<div class="buttons">
     @for (int i = 0; i < 5; i++)
     {
         var index = i;
         <button type="button" class="btn btn-primary" onclick="@((e) => ButtonClicked(index))">Button @i</button>
     }
 </div>
 @code {
  
     private void ButtonClicked(int index)
     {
         Console.WriteLine("Button clicked with index:" + index);
     }
 } 

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.