Search code examples
routesasp.net-mvc-routingmauimaui-blazor

MAUI Blazor Routing bug?


My routes work fine in a regular Blazor application, but don't in Blazor MAUI.

@page "/"
@page "/logitemAdd/{logItemKey?}"

My page answers to both of these routes, but in MAUI, the parameter is not getting passed in.

If I remove the first route, the parameter gets passed in.

//////////////////////////////////////

The issue occurs when using NavigateTo.

Here is my Index.razor page. Note its route of "/Index" and not "/"

@page "/Index"
@inject NavigationManager NavMan

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<div>
    <a onclick="@navto" href="">test link</a>
</div>

@code{

    public void navto()
    {
        NavMan.NavigateTo("/fetchdata/myVariable");
    }
}

Here is my FetchData.razor, note the 2 routes.

When you click on the link in Index the NaviateTo fires, but the parameter is not passed.

If you take the "/" route off the page, the parameter is passed successfully.

@page "/"
@page "/fetchdata/{logItemKey?}"
@using MauiApp2.Data
@inject WeatherForecastService ForecastService

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from a service.</p>

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Date</th>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in forecasts)
            {
                <tr>
                    <td>@forecast.Date.ToShortDateString()</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    [Parameter]
    public string logItemKey { get; set; }
    private WeatherForecast[] forecasts;

    protected override async Task OnInitializedAsync()
    {
        forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
    }
}

Solution

  • I have done a sample to test and find the route with the parameter can work well.

    The code in the razor:

    @page "/fetchdata"
    @page "/fetchdata/{logItemKey?}"
    
    <p>@logItemKey</p>
    

    The code to get the parameter:

    @code {
    private WeatherForecast[] forecasts;
    
    [Parameter]
    public string logItemKey { get; set; }
    protected override async Task OnInitializedAsync()
    {
        forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
    }
    }
    

    And the div in the ui:

    <div>
        <a href="/fetchdata/test">test link</a>
    </div>