Q:

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

0

This code will help you to understand how to call a function or method from the generated DOM button.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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);
     }
 } 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now