How can I load the same Blazor page hitting same url with different parameters and show the parameter to UI in Blazor?

I am new to Web/Blazor development, so I can't find how to search the following question.

I am currently working at a Blazor.Server project in .NET 6 and I want to load the same page hitting one of the following urls:

https://localhost:7226/1 https://localhost:7226/2 https://localhost:7226/3

Hitting every time one of the above urls, I want to load the same Index.razor page and at the same time I need to read the parameter (1,2, or 3) to a variable as a parameter and show the same page with a tag element that shows the Id/parameter number.

How can I implement this functionallity?


Solution 1:

You can do that as described below:

@page "/"
@page "/{id:int}"

<div>ID: @ID</div>

@code {

    [Parameter]
    public int? ID { get; set; }

}
  1. Define a parameter property named ID, and annotated with the ParameterAttribute attribute

  2. Add a second @page directive with a route template that defines a place holder for the ID parameter, with the constraint that it should be of type int.

  3. Note that the type of the parameter property is nullable; that is int?. Without it when you run the app for the first time without adding a number to the url, ID will contain 0... you'll see on the screen the string ID: 0, as this is the default value for the int type. But if you use int?, you'll get the string ID:

  4. Note that this is the way to do that in .Net5.0 and below. In .Net6.0 you can use optional route parameters.

  5. .Net6.0, using optional parameters:

     @page "/{id:int?}"
    
      <div>ID: @ID</div>
    
      @code {
    
      [Parameter]
      public int? ID { get; set; }
    
      }