How to show a list of information on the fly in a razor component

和自甴很熟 提交于 2021-02-08 07:22:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!