Home > OS >  Using Event Callback in a foreach loop in Blazor
Using Event Callback in a foreach loop in Blazor

Time:06-13

I don't know if this is a bug, but I'm getting an unexpected behaviour. I get it, when I modify microsoft doc "EventCallback" enter image description here

Shared/Parent.razor:

enter image description here

Expected Result: I get a list of buttons with different labels with the following Labels => "cow", "dog", "pig", "rat". And when I click on any of the button, I should get a pop-up alert displaying the label text of the button I clicked.

Actual Result: I get a list of buttons with different labels with the following Labels => "cow", "dog", "pig", "rat". But when I click on the button, I get a pop-up alert displaying "rat" regardless of whatever button I'm clicking.

I don't know, is this a bug? If it is not a bug, how do I get my expected result?

CodePudding user response:

This is happening due to variable scoping in lamda expression.

Change

@inject IJSRuntime JS;

@for (var i = 0; i < DataSource.Count; i  )
{
    var local_i = i;
    var local_v = @DataSource[local_i];
    <div>
       <button 
       @onclick="() => OnClickCallback(local_v)">@DataSource[i]
       </button>
    </div>
}

In codebehind

@code {

public List<string> DataSource = new List<string>{"cow", "dog", "pig", "rat"};

   private async Task OnClickCallback(string s)
   {
   Console.WriteLine(s);
   await JS.InvokeVoidAsync("alert", s);  
   }

 }

Proof here

  • Related