1

A razor page is currently constructing a page like this:

      @*...*@
<Template>
<Items>
 <Foo />

   @foreach (var pin in Helper.GetPins()) {
      @*... using pin in control with custom template etc.. *@
   }

 <Bar />
</Items>
</Template>
      @*...*@

The method in Helper.GetPins() looks like this:

public IEnumerable<Pin> GetPins() {
   _PinData = DataHelper.SynchronousRequest();
   return _PinData;
}

Now I have made my GetPins async:

public async Task<IEnumerable<Pin>> GetPinsAsync() {
   _PinData = await DataHelper.AsyncRequest();
   return _PinData;
}

Is it possible to use this GetPinsAsync like this in my Blazor razor page?

If so, how should this be done? Like this:

@foreach (var pin in Helper.GetPinsAsync()) {
  @*... using pin in control with custom template etc.. *@
}

Or should something like await foreach be used?

https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#asynchronous-streams

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
juFo
  • 17,849
  • 10
  • 105
  • 142
  • have you tried await foreach? – Maytham Fahmi May 19 '22 at 07:26
  • 1
    looks like await foreach can't be used in razor markup itself only in the code block https://newbedev.com/can-you-use-iasyncenumerable-in-razor-pages-to-progressively-display-markup#:~:text=You%20can%27t%20write%20await%20foreach%20on.razor%20template%20code.,workaround%2C%20you%20can%20write%20it%20at%20%40code%20section%3A – juFo May 19 '22 at 07:37
  • `@foreach(var pin in await Helper.GetPinsAsync())`. Yes you can use await's in the Razor markup area. – Brian Parker May 19 '22 at 08:02
  • 3
    My answer would be to get the data out of the component. Do the data retrieval in a service - in this case probably a transient PinService - and then consume it in the component. Do you need to retrieve the Pins collection every time the component gets re-rendered? If no then why do so? If yes then drive the update based on when the Pins collection updates. Retrieving data in components burdens the UI Renderer making it slower and less responsive. – MrC aka Shaun Curtis May 19 '22 at 08:15

0 Answers0