3

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

americanslon
  • 4,048
  • 4
  • 32
  • 57
  • You should define your loop like this: @for (var i = 0; i < 3; i++) { var local = i;
    }
    – enet May 05 '20 at 18:46
  • See this: https://stackoverflow.com/a/54813295/6152891 – enet May 05 '20 at 18:55
  • Does this answer your question? [For loop not returning expected value - C# - Blazor](https://stackoverflow.com/questions/54812427/for-loop-not-returning-expected-value-c-sharp-blazor) – enet May 05 '20 at 18:56
  • Yep, thanks. I don't know how I missed this. Rough day. – americanslon May 05 '20 at 18:58

2 Answers2

3

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]" />              
}
Vencovsky
  • 28,550
  • 17
  • 109
  • 176
2
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...

enet
  • 41,195
  • 5
  • 76
  • 113