Search code examples
c#asp.net-web-apixamarin.formspicker

Passing data from web api on the main page to the details page in xamarin forms


Here is how my code looks like for the page that has data:

private async Task GetLeaveBalance() {
    try
    {
        Uri = "http://192.168.42.35/API/api/leave/getbalance/"+ empId + "/"+ companyId;
        client = new HttpClient();

        var authHeaderValue = basic;
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);

        HttpResponseMessage response = await client.GetAsync(Uri);
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();

        if (response.IsSuccessStatusCode)
        {
            var emp = JsonConvert.DeserializeObject<List<Leave>>(responseBody);
            dataGrid.ItemsSource = emp;
            UserDialogs.Instance.HideLoading();
        }
    }
    catch (HttpRequestException e)
    {
        Console.WriteLine("\nException Caught!");
        Console.WriteLine("Message :{0} ", e.Message);
        UserDialogs.Instance.ShowError(e.Message);
    }
}

private void Button_Clicked(object sender, EventArgs e)
{
    Navigation.PushAsync(new Details());
}

My Second page(Details Page) has a picker which needs to be populated by data that I get from the emp variable so how can I pass data from the first page to the second page(Details Page)?


Solution

  • You can pass through MessagingCenter aswell, here is some steps.

    First in your SecondPage you register an messagingcenter task.

    MessagingCenter.Subscribe<SecondPage(you can create a empty interface if you want to use as type),string>(this, "PopulateSecondPage", (sender,DataFromMainPage) =>
                {
                    //your code to handle DataFromMainPage
                });
    

    then pass the data using

        var page = new SecondPage();
    
        Navigation.PushAsync(page);
    
       MessagingCenter.Send<MainPage>(page, "PopulateSecondPage","Data you want to pass");