Search code examples
c#.netnavigationmaui.net-maui.shell

Trying to pass query parameter in MAUI


This is the function that changes location:

string restaurantId = (string)e.Parameter;

Console.WriteLine(restaurantId);

await Shell.Current.GoToAsync($"location?restaurantId={restaurantId}");

Param is not undefined and it is consoled there. And the page changes, but the query param is empty string:

[QueryProperty("RestaurantId", "restaurantId")]
internal partial class LocationModel : ObservableObject
{
    [ObservableProperty]
    public string restaurantId;
       
    public LocationModel() 
    {
        Console.WriteLine(RestaurantId); // EMPTY
    }
}

This is AppShell.cs where routes are registered:

public partial class AppShell : Shell
{
    public AppShell()
    {
        InitializeComponent();
        Routing.RegisterRoute("login", typeof(LoginPage));
        Routing.RegisterRoute("home", typeof(MainPage));
        Routing.RegisterRoute("location", typeof(LocationPage));
    }
}

What am I doing wrong?


Solution

  • One way to fix this is to use the [QueryProperty] on your LocationPage (the Page) and not on the LocationModel (the ViewModel), and then pass it along from the Page to the ViewModel.

    LocationPage.xaml.cs

    [QueryProperty(nameof(Id), "restaurantId")]
    public partial class LocationPage : ContentPage
    {
        private LocationModel _viewModel;
    
        public string Id
        {
            set => _viewModel.RestaurantId = value;
        }
    
        public LocationPage()
        {
            InitializeComponent();
            BindingContext = _viewModel = new LocationModel();
        }
    }
    

    LocationModel

    public partial class LocationModel : ObservableObject
    {
        [ObservableProperty]
        public string restaurantId;
    }
    

    This way you can retrieve the query parameter and pass it along to the ViewModel. You'll have to implement the logic for loading data in the ViewModel according to the passed RestaurantId yourself. You could also do this using a method, such as Load(string restaurantId) instead of using a property.

    You can read more about how query parameters work in the official documentation.