Home > Blockchain >  Blazor Looping, Closures and Binding
Blazor Looping, Closures and Binding

Time:05-22

I broke this down to a simple example of Looping through some stuff but breaking it out in levels. I'm instantiating a local copy in the inner loop but that doesn't seem to work. When you try and change a value in the input it changes them all to the counter variable.

Here's the code in Blazor Fiddle https://blazorfiddle.com/s/d02wswws


@for (var i = 0; i < levels; i  )
{
    <div>Level @i</div>
    @for (var j = 0; j < stuffPerLevel; j  )            
    {
        int copy = allStuffCounter;
        <input type="text" @bind="stuff[copy]" @bind:event="oninput" />
        <div>@stuff[copy]</div>
        if(allStuffCounter < stuffCounterLimit) allStuffCounter  ;
    }
}

@code
{
  string[] stuff = {"some stuff 1", ... ,"some stuff 20"};
                    
  int allStuffCounter = 0;
  int levels = 3;
  int stuffPerLevel = 4;
  int stuffCounterLimit = 11;
}

CodePudding user response:

Copy and test...

@for (var i = 0; i < levels; i  )
{
    <div>Level @i</div>

    @for (var j = 0; j < stuffPerLevel; j  )
    {
         int copy = allStuffCounter;

        <input @bind="stuff[copy]" @bind:event="oninput" type="text" />

        <div>@stuff[copy]</div>
        allStuffCounter  ;

    }

}

@code
{
    string[] stuff = { "some stuff 1", "some stuff 2", "some stuff 3", "some stuff 4",
        "some stuff 5", "some stuff 6","some stuff 7","some stuff 8","some stuff 9",
        "some stuff 10","some stuff 11","some stuff 12","some stuff 13","some stuff 14",
        "some stuff 15","some stuff 16","some stuff 17","some stuff 18","some stuff 19", "some stuff 20" };


    int allStuffCounter = 0;
    int levels = 3;
    int stuffPerLevel = 4;
    // Superfluous...
   // int stuffCounterLimit = 11;

    protected override void OnAfterRender(bool firstRender)
    {
        allStuffCounter=0;
    }
}

CodePudding user response:

The problem is the scope of the allStuffCounter. Any change (oninput) will trigger a re-render but starting witht the old value of allStuffCounter .

The fix:


@{ int allStuffCounter = 0; } 

@for (var i = 0; i < levels; i  )
{    
   int copy = allStuffCounter;
   ...      
   if(allStuffCounter < stuffCounterLimit) allStuffCounter  ;
    
}

@code
{                  
  //int allStuffCounter = 0;
}
  • Related