Storing data in the URL
At first glance, this option might sound horrific but it’s not. Data, in this case, can be the blog post ID or the page number if we use paging. Typically, the things you want to save in the URL are things you want to be able to link to later on, such as blog posts in our case.
To read a parameter from the URL, we use the following syntax:
@page "/posts/{PageNumber:int}"
The URL is posts
followed by the page number (for paging through blog posts) of the post.
To find that particular route, PageNumber
must be an integer; otherwise, the route won’t be found.
We also need a public
parameter with the same name:
[Parameter]
public int PageNumber{ get; set; }
If we store data in the URL, we need to make sure to use the OnParametersSet
or OnParametersSetAsync
method; otherwise, the data won’t get reloaded if we change the parameter. If the parameter changes, Blazor won’t run OnInitializedAsync
again...