This code will help you to understand how to call a function or method from the generated DOM button.
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); } }
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Generally, we are using lambda expressions to create DOM elements dynamically like in the following code snippet.
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.
need an explanation for this answer? contact us directly to get an explanation for this answer