简体   繁体   中英

Blazor Looping, Closures and Binding

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;
}

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;
}

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM