Why doesn't the binding work with an array and a for loop in my example (blazor)?

Viewed 771

I have a situation where I have a 0-n fields that may need to be populated. I accomplish that by trying to bind to List<double> in a for loop as such

@for (var i = 0; i < 3; i++)
{                    
    <input type="text" @bind="TraineeValues[i]" />              
}

The issue is that underlying list values don't seem to be updating. Fiddle below

https://blazorfiddle.com/s/gfhw59v4

2 Answers

You need to create another variable inside the loop for getting the correct variable

@for (var i = 0; i < 3; i++)
{                 
    var ii = i;   
    <input type="text" @bind="TraineeValues[ii]" />              
}
Your for loop should contain a local variable like this:

 @for (var i = 0; i < 3; i++)
 {    
     var localVariable = i;                
     <input type="text" @bind="TraineeValues[localVariable]" />              
  }

This is standard C# behavior where your code has access to a variable and not to the value of the variable. You have to define a variable which is local to the for loop; that is, this variable is defined at each iteration of the loop, otherwise it's the same variable across all iterations, and your code is going to use the same value contained in the variable when the loop ends.

See also this...

Related