Json HTTpClient populate Control SfAutoComplete

Hi, Mr. Syncfusion.

How to populate SfAutoComplete from Json ?
My code is:

ModeloCustomers.cs
using System;
namespace MPG.Modelos
{
    public class ModeloDatosClientes
    {
        public string Cliente_Id { get; set; }
        public string Cliente_Nombre { get; set; }
        public string Cliente_Correo { get; set; }
        public string Cliente_CorreoCC { get; set; }
        public string Cliente_Direccion { get; set; }
        public string Cliente_Contacto { get; set; }
        public string Cliente_Phone { get; set; }
        public string Cliente_Fax { get; set; }
        public string Cliente_Celular { get; set; }
        public string Cliente_Notas { get; set; }
    }
}

PageView.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net.Http;
using System.Text;
using MPG.Modelos;
using Newtonsoft.Json;
using Xamarin.Forms;
using Syncfusion.SfAutoComplete.XForms;

public partial class InvoicePageAdd : ContentPage
    {
        private List<ModeloDatosClientes> propiedadesCual;
        public InvoicePageAdd()
        {
            InitializeComponent();
            LoadPropiedades();
        }

        private async void LoadPropiedades()
        {
            string jsonResDetalles = string.Empty;
            try
            {
                HttpClient Cliente = new HttpClient();
                Cliente.BaseAddress = new Uri("http://www.mpg.com");
                string url = string.Format("/json_loadclientes.php");
                var resultado = await Cliente.GetAsync(url);
                jsonResDetalles = resultado.Content.ReadAsStringAsync().Result;
            }
            catch (Exception)
            {
                await DisplayAlert("Error", "Your Smartphone Should Be Connected to Internet", "Ok");
                return;
            }
            propiedadesCual = JsonConvert.DeserializeObject<List<ModeloDatosClientes>>(jsonResDetalles);
        }
 }

PageView.xaml
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:autocomplete="clr-namespace:Syncfusion.SfAutoComplete.XForms;assembly=Syncfusion.SfAutoComplete.XForms"
xmlns:ListCollection="clr-namespace:System.Collections.Generic;assembly=netstandard"
x:Class="MPG.Pages.InvoicePageAdd">
<ContentPage.Content>
<StackLayout VerticalOptions="Start" HorizontalOptions="Start" Padding="10,2,10,2">
<inputLayout:SfTextInputLayout Hint="Property" ContainerType="Outlined">
<autocomplete:SfAutoComplete SuggestionMode="Contains" HeightRequest="25" BorderColor="Green" WatermarkColor="Green"/>
</inputLayout:SfTextInputLayout>
</StackLayout>
</ContentPage.Content>
</ContentPage>

14 Replies 1 reply marked as answer

SS Suganya Sethuraman Syncfusion Team October 6, 2020 06:29 AM UTC

Hi EDGAR,

Greetings from Syncfusion.

We have analyzed your query and prepared sample with the JSON Data based on your requirement. Please find the sample from below link for your reference.

Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/AutoComplete_PinCodeSearch_3208948818.zip

Please check with the above sample and let us know if you have any concerns.

Regards,
Suganya Sethuraman.
 



EG EDGAR GARCIA October 6, 2020 10:42 AM UTC

Sorry, the sample implementation is very different, because I am not using viewmodel. 
Why my code do not working ? i have a simple code. Can you check it again ?

my view is: PageView.xaml

<StackLayout VerticalOptions="Start" HorizontalOptions="Start" Padding="10,2,10,2">
        <autocomplete:SfAutoComplete SuggestionMode="Contains" HeightRequest="25" DataSource="{Binding listaFinal}" DisplayMemberPath="Cliente_Nombre"/>
</StackLayout>

my model: ModeloCustomers.cs
using System;
namespace MPG.Modelos
{
    public class ModeloDatosClientes
    {
        public string Cliente_Id { get; set; }
        public string Cliente_Nombre { get; set; }
        public string Cliente_Correo { get; set; }
    }
}

PageView.cs
public partial class InvoicePageAdd : ContentPage
    {
        private List<ModeloDatosClientes>propiedadesCual;
        public InvoicePageAdd()
        {
            InitializeComponent();
            LoadPropiedades();
        }

        private async void LoadPropiedades()
        {
            string jsonResDetalles = string.Empty;
            try
            {
                HttpClient Cliente = new HttpClient();
                Cliente.BaseAddress = new Uri("http://www.mpg.com");
                string url = string.Format("/json_loadclientes.php");
                var resultado = await Cliente.GetAsync(url);
                jsonResDetalles = resultado.Content.ReadAsStringAsync().Result;
            }
            catch (Exception)
            {
                await DisplayAlert("Error", "Your Smartphone Should Be Connected to Internet", "Ok");
                return;
            }
            propiedadesCual = JsonConvert.DeserializeObject<List<ModeloDatosClientes>>(jsonResDetalles);
        }
 }



SS Suganya Sethuraman Syncfusion Team October 7, 2020 03:49 PM UTC

Hi EDGAR,
 
We are currently validating on this and we will update the details on or before October 9, 2020. We appreciate your patience until then.

Regards,
Suganya Sethuraman.
 



SS Suganya Sethuraman Syncfusion Team October 8, 2020 03:26 PM UTC

Hi EDGAR,

We have analyzed your requirement based on the code snippet provided. Provided link has not opened. So, we have prepared the sample by using another link. To render the data, we need to set DataSource and DisplayMemberPath properties to the SfAutoComplete. Please have the sample for your reference.
 
Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/JSONListUsage-1447851344 

Please check the sample if it meets your requirements and let us know if you have any concerns.

Regards,
Suganya Sethuraman.
 


Marked as answer

EG EDGAR GARCIA October 12, 2020 02:06 PM UTC

Thanks, Work 


SS Suganya Sethuraman Syncfusion Team October 13, 2020 05:17 AM UTC

Hi EDGAR,

Thanks for the update.

We are glad to know that the given solution works. Please let us know if you need any further assistance.

Regards,
Suganya Sethuraman.
 



EG EDGAR GARCIA October 27, 2020 03:23 AM UTC

Hi, am i again.

How to get/retrieve the value selected ? My Json return (HTTP) Cliente_Nombre, Cliente_Id.
 Cliente_Nombre is DisplayMemberPath but i need retrieve or catch the value Cliente_Id.

1) View Model:

namespace InvoiceMPG
{
    public class ViewModel : INotifyPropertyChanged
    {
        private ObservableCollection<DataClientes> clientes;

        public ViewModel()
        {
            jsonDataCollection = new List<ModeloDatosClientes>();
            GetInformation();
        }
        private async void GetInformation()
        {
            var httpClient = new HttpClient();
            var response = await httpClient.GetStringAsync("https://www.invoicempg.com/xamarin/json_loadclientes.php");
            jsonDataCollection = JsonConvert.DeserializeObject<List<ModeloDatosClientes>>(response);
            this.Clientes = new ObservableCollection<DataClientes>();
            foreach (var data in jsonDataCollection)
            {
                Clientes.Add(new DataClientes()
                {
                    ClienteNombre = data.Cliente_Nombre,
                    ClienteID = data.Cliente_Id,
                });
            }
        }
        private List<ModeloDatosClientes> jsonDataCollection;
        public ObservableCollection<DataClientes> Clientes
        {
            get
            {
                return this.clientes;
            }
            set
            {
                this.clientes = value;
                this.RaiseOnPropertyChanged("Clientes");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void RaiseOnPropertyChanged(string propertyName)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

2) XAML/File: 
    <autoComplete:SfAutoComplete
            x:Name="PropiedadesCualFue"
            BorderColor="Green"
            DataSource="{Binding Clientes, Mode=TwoWay}"
            DisplayMemberPath="ClienteNombre"
            SuggestionMode="Contains"
            AutoCompleteMode="Suggest"
            Watermark="Search property"
            WatermarkColor="Green"
            TextHighlightMode="FirstOccurrence"
             HighlightedTextColor="Red"
             HighlightedTextFontAttributes="Bold"
 />


3) DataClientes.cs:
using System;
namespace InvoiceMPG.Modelos
{
    public class DataClientes
    {
        public string ClienteNombre { get; set; }
        public string ClienteID { get; set; }
    }
}

4) ModeloDatosClientes.cs:
using System;
namespace InvoiceMPG.Modelos
{
    public class ModeloDatosClientes
    {
        public string Cliente_Id { get; set; }
        public string Cliente_Nombre { get; set; }
    }
}

                


SS Suganya Sethuraman Syncfusion Team October 27, 2020 08:02 AM UTC

Hi EDGAR,

We have analyzed your requirement. We have achieved your requirement using the SelectedValue and SelectedValuePath APIs. I have added SelectedValue property in the ViewModel class. We can retrieve ClienteID in the SelectedValue(ViewModel) property set. Please have the modified sample,

Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/JSONListAutoComplete-988006230

Please check the sample if it meets your requirements and let us know if you have any concerns.

Regards,
Suganya Sethuraman.
 



EG EDGAR GARCIA October 31, 2020 03:55 PM UTC

Awesome. Work..appreciate for your help 


SS Suganya Sethuraman Syncfusion Team November 2, 2020 05:50 AM UTC

Hi EDGAR,

Thanks for the update.

We are glad to know that the given solution works. Please let us know if you need any further assistance.

Regards,
Suganya Sethuraman.
 



EG EDGAR GARCIA November 3, 2020 12:43 AM UTC

The last question: How to get another element and assign to label field. When i select the element from SfComboBox, i can get the value ClienteID and  ClienteNombre but i want also get ClienteCorreoMain  and put it <label x:"nameVariable"> or binding. 

Example:

1) View.

        <StackLayout Padding="10,2,10,2">
                    <combobox:SfComboBox
                        x:Name="PropiedadesCualFue"
                        DataSource="{Binding Clientes, Mode=TwoWay}"
                        DisplayMemberPath="ClienteNombre"
                        SelectedValue="{Binding SelectedValue, Mode=TwoWay}"
                        SelectedValuePath="ClienteID"/>
        </StackLayout>

1) ViewModel.

namespace InvoiceMPG
{
    public class ViewModel : INotifyPropertyChanged
    {
        private ObservableCollection<DataClientes> clientes;

        public ViewModel()
        {
            jsonDataCollection = new List<ModeloDatosClientes>();
            GetInformation();
        }
        private async void GetInformation()
        {
            var httpClient = new HttpClient();
            var response = await httpClient.GetStringAsync("https://www.invoicempg.com/xamarin/json_loadclientes.php");
            jsonDataCollection = JsonConvert.DeserializeObject<List<ModeloDatosClientes>>(response);
            this.Clientes = new ObservableCollection<DataClientes>();
            foreach (var data in jsonDataCollection)
            {
                Clientes.Add(new DataClientes()
                {
                    ClienteID = data.Cliente_Id,
                    ClienteNombre = data.Cliente_Nombre,
                    ClienteCorreoMain = data.Cliente_Correo,
                });
                SelectedValue = Clientes[0].ClienteID;
                SelectedValueEmail = Clientes[0].ClienteCorreoMain;
            }
        }
        private List<ModeloDatosClientes> jsonDataCollection;
        public ObservableCollection<DataClientes> Clientes
        {
            get
            {
                return this.clientes;
            }
            set
            {
                this.clientes = value;
                this.RaiseOnPropertyChanged("Clientes");
            }
        }

        private object selectedValue;
        public object SelectedValue
        {
            get
            {
                return this.selectedValue;
            }
            set
            {
                this.selectedValue = value;
                this.RaiseOnPropertyChanged("SelectedValue");
            }
        }

        private object selectedValueEmail;
        public object SelectedValueEmail
        {
            get
            {
                return this.selectedValueEmail;
            }
            set
            {
                this.selectedValueEmail = value;
                this.RaiseOnPropertyChanged("SelectedValueEmail");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void RaiseOnPropertyChanged(string propertyName)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}



SS Suganya Sethuraman Syncfusion Team November 3, 2020 07:25 AM UTC

Hi EDGAR,

We have analyzed your requirement. We have achieved your requirement by using the SelectionChanged event as the following code snippet,

Code snippet:
 
        public void AutoCompleteSelectionChanged(Syncfusion.SfAutoComplete.XForms.SelectionChangedEventArgs selectionChangedEventArgs) 
        { 
            if (selectionChangedEventArgs.Value is DataClientes) 
            { 
                SelectedValueEmail = (selectionChangedEventArgs.Value as DataClientes).ClienteCorreoMain; 
            } 
            else if (selectionChangedEventArgs.Value == null) 
            { 
                SelectedValueEmail = null; 
            } 
        } 

Please have the sample for your reference,

Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/JSONListUsage_AutoComplete1776607146

Please check the sample if it meets your requirements and let us know if you have any concerns.

Regards,
Suganya Sethuraman.
 



EG EDGAR GARCIA November 6, 2020 03:07 AM UTC

Awesome. Thanks. Work perfect


SS Suganya Sethuraman Syncfusion Team November 6, 2020 06:42 AM UTC

Hi EDGAR,

Thanks for the update.

We are glad to know that the given solution works. Please let us know if you need any further assistance.

Regards,
Suganya Sethuraman.
 


Loader.
Up arrow icon