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

4
  • You should define your loop like this: @for (var i = 0; i < 3; i++) { var local = i; <div class="field"> <input type="text" @bind="@TraineeValues[local]" /> </div> } Commented May 5, 2020 at 18:46
  • See this: stackoverflow.com/a/54813295/6152891 Commented May 5, 2020 at 18:55
  • Does this answer your question? For loop not returning expected value - C# - Blazor Commented May 5, 2020 at 18:56
  • Yep, thanks. I don't know how I missed this. Rough day. Commented May 5, 2020 at 18:58

2 Answers 2

7

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]" />              
}
Sign up to request clarification or add additional context in comments.

Comments

3
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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.