I am getting more and more used to using .Net Core
but have some 'simple' questions about using asychronous tasks.
I have read throught the .Net tutorials on Razor pages for web apps on MSDN/Microsot but I want to figure out how to:
- Click a button on my page (page is
GetFiles.cs
andGetFiles.cshtml.cs
) called "Get Files" - think this isn't hard - Button "Get Files" gets disabled and series of sequentail tasks starts - disable button is simple but how to call the tasks
- Page does not do a full refresh but keeps updating the page (appending text) as tasks are done - not sure on this
- When button gets disable text below says something like "Task started..."
- First task gets started and queries a database and text gets appended to above prior to query as "Query started" and appended after query finishes "Query ended"
- Next task starts and text is appended as "Create file started" and a file is created then with query data from above and then when it finishes text is appended as "File creation finished"
I see this method:
public async Task<IActionResult> OnPostAsync()
{
// Do the x number of tasks and updates in here (number of tasks my vary depending on query results)
// return Page?
return ?
}
What is the easiest way to make a progree/task loop like this?
CodePudding user response:
A Razor page generates all of the HTML for a page in one go and sends it to the browser as a response. You can't send part of the HTML and then update other parts incrementally without incorporating other technologies. If you have multiple background tasks running as part of the Razor page execution, they all have to complete before the HTML is rendered.
You could use SignalR to update parts of the page based on changes on the server after the initial page has rendered, but it might be simpler to use client side script to make various asynchronous calls (XmlHttpRequest or Fetch) to named handler methods that are responsible for executing the background tasks and then update part of the page with the response to those calls.
Personally, I would use the Fetch API to call into named handler methods that return partial views (snippets of HTML) for this, or if the web app relies heavily on this requirement, I would more likely build a Blazor WebAssembly app.