问题
I have a database and a lot of entries in a table. I want to show those entries on a webpage, using blazor.
I have tried loading the entries using context.tableName.Load()
and context.tableName.Local
and iterating through the entries using
@foreach(var entry in localList){
<p>@entry.Name</p>
}
That works fine.. but it first loads all the data from the database and when it finally has finished, it starts rendering the page/results.
I want to show the results that have been loaded immediately, popping up responsive on the webpage as the loading continues. Any ideas how I would implement that?
Thanks!
回答1:
What you describe matches what IAsyncEnumerable<>
does.
Just for fun I adapted the standard starter app a little:
In WeatherForecastService :
public async IAsyncEnumerable<WeatherForecast> GetForecastAsync(DateTime startDate)
{
var rng = new Random();
for (int i = 0; i < 77; i++)
{
yield return new WeatherForecast
{
Date = startDate.AddDays(i),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
};
await Task.Delay(100);
}
}
and in the FetchData.razor page:
List<WeatherForecast> forecasts = new List<WeatherForecast>();
protected override async Task OnInitializedAsync()
{
await foreach (var forecast in ForecastService.GetForecastAsync(DateTime.Now))
{
forecasts.Add(forecast);
StateHasChanged();
}
}
be aware that this is not a very efficent way of moving data but it might work for some scenarios.
来源:https://stackoverflow.com/questions/59308596/how-to-show-a-list-of-information-on-the-fly-in-a-razor-component