Managing State
Storing Data On Server Side
There are numerous
methods available for storing data on the server. It's important to keep in
mind that Blazor WebAssembly will always require an API. In contrast, Blazor
Server can access server-side resources directly without needing an API.
If you're developing a
Blazor Server application and don't want to switch to Blazor WebAssembly, you
should choose direct access. We can initially utilize direct server access and
transition to an API later if we choose to. In terms of data storage options,
we have the ability to store data in Blob storage, key-value storage, a
relational database, or table storage. The options are virtually limitless. As
long as .NET can interact with the technology, we can implement it.
Storing Data In URL
Data, in this case, could
refer to the ID of the blog post or the specific page number when pagination is
being utilized. To read a parameter from the URL, we can use the following
syntax-
@page
"/post/{BlogPostId:int}"
The URL is post
followed by Id of the post. To find that particular route, BlogPostId
must be an integer, otherwise the route won't be found. We will also need a
public parameter with the same name.
When storing data in the
URL, it's important to utilize the OnParametersSet or OnParametersSetAsync
methods; otherwise, the data will not refresh if the parameter changes. If a
parameter is modified, Blazor does not execute OnInitializedAsync again.
Hence, our post.razor
component fetches the items that vary depending on the URL parameter in OnParametersSet,
while it retrieves the elements that remain constant regardless of the
parameter in OnInitializedAsync. We can also use optional parameters by
specifying them as nullable like this-
@page
"/post/{BlogPostId:int?}"
Route Constraints
When we define the type
for a parameter, this is referred to as a route constraint. We introduce a
constraint so that the match will occur only if the parameter value can be
transformed into the type we've indicated. The constraints listed below are
available:
• bool
• datetime
• decimal
• float
• guid
• int
• long
The components of the URL
will be transformed into a CLR object. Hence, it's crucial to apply an
invariant culture when incorporating them into a URL.
Using A Query String
We can also read data
from the query string. NavigationManager gives us access to the URI, so
by using this code, we can access the query string parameters-
@inject
NavigationManager Navigation
@code{
var
query = new Uri(Navigation.Uri).Query;
}
Conclusion
We have successfully
learnt about various methods of storing data.
Comments
Post a Comment