@page "/"
@for (int i = 0; i < foos.Count; i++)
{
int iCopy = i;
var foo = foos.GetFoos()[i];
<div class="col-3">
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-primary" @onclick="@(() => InsertFooAt(iCopy))">Insert above</button>
<button type="button" class="btn btn-primary" @onclick="@(() => RemoveFooAt(iCopy))">Delete</button>
<button type="button" class="btn btn-primary" @onclick="@(() => InsertFooAt(iCopy+1))">InsertBelow</button>
</div>
</div>
<div class="col-3">
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-primary" @onclick="@(() => InsertFooAtAsync(iCopy))">Insert above async</button>
<button type="button" class="btn btn-primary" @onclick="@(( ) => RemoveFooAtAsync(iCopy))">Delete async</button>
<button type="button" class="btn btn-primary" @onclick="@(() => InsertFooAtAsync(iCopy+1))">InsertBelow async</button>
</div>
</div>
<div class="col-6">
<input type="text" class="form-control" @bind-value="@foo.Data"/>
</div>
}
@if (foos.Result == null)
{
<div class="spinner-border" role="status">
<span class="visually-hidden">Loading...</span>
</div>
}
else
{
<span class="border-success">@foos.Result</span>
}
@code {
FooCollection foos = new FooCollection();
void InsertFooAt(int index)
{
foos.CreateFooAt(index);
}
void RemoveFooAt(int index)
{
foos.RemoveFooAt(index);
}
async Task InsertFooAtAsync(int index)
{
await foos.CreateFooAtAsync(index);
await InvokeAsync(StateHasChanged);
}
async Task RemoveFooAtAsync(int index)
{
await foos.RemoveFooAtAsync(index);
await InvokeAsync(StateHasChanged);
}
public class Foo
{
public string Data { get; set; }
public Foo() { Data = "bar"; }
}
public class FooCollection
{
public int Count => foos.Count;
public string? Result { get; private set; }
private List<Foo> foos;
public FooCollection()
{
foos = new List<Foo>() { new Foo() };
Result = foos.Single().Data;
}
public IList<Foo> GetFoos() { return foos; }
public void CreateFooAt(int index)
{
foos.Insert(index, new Foo());
UpdateResult();
}
public void RemoveFooAt(int index)
{
foos.RemoveAt(index);
UpdateResult();
}
public async Task CreateFooAtAsync(int index)
{
foos.Insert(index, new Foo());
await UpdateResultAsync();
}
public async Task RemoveFooAtAsync(int index)
{
foos.RemoveAt(index);
await UpdateResultAsync();
}
private void UpdateResult()
{
Result = null;
Thread.Sleep(1000); // Do some expensive operation on the data
Result = foos.Select(f => f.Data).Aggregate((a, b) => a + ", " + b);
}
private async Task UpdateResultAsync()
{
Result = null;
await Task.Delay(1000); // Do some expensive operation on the data
Result = foos.Select(f => f.Data).Aggregate((a, b) => a + ", " + b);
}
}
}