Home > Mobile >  In .NET MAUI can you pass data transfer objects as query string parameters from one View to another?
In .NET MAUI can you pass data transfer objects as query string parameters from one View to another?

Time:11-27

I have worked through the .NET MAUI "Create a .NET MAUI App" startup tutorial. I modified the tutorial a bit to use a sqlite database instead of files for each row in the CollectionView. When they go to edit a row in the collection view they pass the id of the DTO of the row to a new view:

await Shell.Current.GoToAsync($"{nameof(NotePage)}?{nameof(NotePage.ItemId)}={SelectedNote.ID}");

and the new view loads the ItemID with the following annotation:

[QueryProperty(nameof(ItemId), nameof(ItemId))]

I was then taking that ItemId and doing another call to the database to return the DTO but since I am loading my data from the database I already have my DTO from the CollectionView and I just want to pass the whole thing over to the new view as some sort of query parameter to save resources. How do I do this?

I saw someone online with a tutorial that showed to pass it like this:

await Shell.Current.GoToAsync(nameof(NotePage), SelectedNote);

But Visual Studio says that my second parameter has to be a bool so I'm guessing that guys tutorial is wrong.

Anyone know if its possible to pass a DTO from a view in this way or something similar?

Thanks,

CodePudding user response:

the docs demonstrate how to do this

Object-based navigation data can be passed with a GoToAsync overload that specifies an IDictionary<string, object> argument:

Animal animal = e.CurrentSelection.FirstOrDefault() as Animal;
var navigationParameter = new Dictionary<string, object>
{
    { "Bear", animal }
};
await Shell.Current.GoToAsync($"beardetails", navigationParameter);

then the receiving page or VM can do this

[QueryProperty(nameof(Bear), "Bear")]
public partial class BearDetailPage : ContentPage
{
    Animal bear;
    public Animal Bear
    {
        get => bear;
        set
        {
            bear = value;
            OnPropertyChanged();
        }
    }

    public BearDetailPage()
    {
        InitializeComponent();
        BindingContext = this;
    }
}
  • Related