1
votes

Is there any way to cache the data that is loaded in the onGetAsync method? For example, we load data from the database in onGetAsync and bind them to our properties.

I'm wondering if there is a way to keep this data cached/persisted so the onPostAsync method doesn't need to reload all of this and hit the database again. Currently we load the data in the constructor of the PageModel so it gets loaded twice.

For example, we have a remove from cart which removes an item from the shopping cart, so we want to continue showing the shopping cart page so a return Page(); happens but we obviously need to reload all the data which is extremely inefficient.

I'm thinking this might have to happen since we have to update the database with our WriteModel anyway.

1
If the data that you want to cache is applicable to all requests, then cache is the best option to use. If it is applicable to a single user, you should look at using Session instead. See more about State Management options in Razor Pages here: learnrazorpages.com/razor-pages/state-management - Mike Brind

1 Answers

0
votes

There are several options for caching in ASP.NET Core. The simplest being an in-memory cache and then expanding to distributed caches using SQL Server or Redis. See these articles for more details:

You are correct the OnPost needs to reload the data to be shown. Web requests are stateless so without caching the data needs to be re-queried. You could possibly change the code to use JavaScript so that the remove from cart option makes an AJAX call to the server and if the item is successfully removed then update the UI. This avoids the roundtrip to reload the data.