In-Memory State Container Service in Blazor
This blog is going to explain how to carry data from page to page or component. In the Blazor application, you can achieve this by injecting application state, dependency injection, and custom class. This state will persist in the browser's memory. So when the user navigates through the browser, they will get the same data. But this data will be cleared when the user refreshes the page.
Let's look at the in-memory state process step by step. This example is going to illustrate how to manage in-memory state values from one child to another.
Step1:
First, I created the StateContainer class.
Step 2: I created this project on a Blazor server. If your project is also a Blazor server, add the following line to Program.cs.
Program.csIf you are using an earlier version of Blazor server 6.0, add the following line to Startup.ConfigureServices.
Startup.csIf your project is Blazor WebAssembly, add the following line to Program.cs.
Program.csStep 3: The first child component is as follows. Here you can see the injected StateContainer using the @inject directive. It has a text box for collecting the movie name and a button to add the movie name to the list. When the user clicks the button, the movie name is sent as a parameter to the SetValue() custom class and added to the movie list.
ChildOne.razorStep 4: Next is the second child component. Here also, theStateContainer is injected using the @inject directive. Here the MovieList will be displayed using the foreach loop.
ChildTwo.razorStep 5: This is an index page. Here the first and second child components are included.
Index.razorThe output of the code above is below. Here you can see that when the user types in the name of the movie and clicks on the button in the first child component, it will add in the second child component.
I hope this helps you. Keep coding.
Comments
Post a Comment