blazorparameter-passingurl-routing

Routing in Blazor does not work, parameter passed is always null


I have a simple razor component looking like this

@page "/einsatz"
@page "/einsatz/{ScaledTable}"

@code {
    [Parameter] 
    public string ScaledTable { get; set; } 

    private string Test { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Test = ScaledTable;   // ScaledTable is NULL here
    }

    protected override async Task OnParametersSetAsync()
    {
        Table = ScaledTable;  // ScaledTable is NULL here
    }
}

I try to call the component with the following URLs

https://localhost:60711/einsatz 

=> ScaledTable is null as expected

https://localhost:60711/einsatz/test 

=> Exception

Failed to load resource: the server responded with a status of 404 () all.css:1
Failed to load resource: the server responded with a status of 404 () site.css:1
Failed to load resource: the server responded with a status of 404 () blazor.server.js:1
... and so on

Failed to load resource: the server responded with a status of 404 ()
telerik-blazor.js:1

https://localhost:60711/einsatz?scaledtable=test 

=> ScaledTable is NULL here also - why!?

If I try this page directives instead:

@page "/einsatz"
@page "/einsatz/{ScaledTable:string}"

I get an exception at startup of the app

System.NullReferenceException: Object reference not set to an instance of an object.

at Microsoft.AspNetCore.Components.Routing.Router.Refresh(Boolean isNavigationIntercepted)
at Microsoft.AspNetCore.Components.Routing.Router.SetParametersAsync(ParameterView parameters)

What am I doing wrong here? What I am misunderstanding here?

Edited 26.02.2023/18:03

First of all, the error for

@page "/einsatz/{ScaledTable:string}"

is by design, since you have not to specify string type for parameter.

Looking further into the exception, using

@page "/einsatz/{ScaledTable}"

I found out, that these errors come from wrong routes, generated for the files in the layout. The try to load

localhost:60711/einsatz/_framework/blazor.server.js

fails with HTTP 404 of cause, because there should be no "einsatz" in this URL, something seems to be wrong here anywhere ...


Solution

  • Finally I found the error I made.

    I have to add the following line to the _layout.cshtml file:

    <head>
       <base href="~/" />
       ....
    

    Don't know where I have lost this, it is part of any new Blazor project.