Model is here :
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XamarinWebServices.Models
{
public class CustomerViewModel
{
public int id { get; set; }
public string name { get; set; }
}
// ViewModel:
public class CustomerVM
{
public CustomerViewModel Data { get; set; }
public ObservableCollection<CustomerViewModel> CustomerList { get; set; }
public CustomerVM()
{
CustomerList = new ObservableCollection<CustomerViewModel>();
}
}
}
XAML file for Picker (Dropdown) :
<?xml version="1.0" encoding="utf-8" ?>
</Picker.Items>
</Picker>
And here is the codeBehind with dynamic data through link [Working with Web Api in Xamarin.forms]:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using XamarinWebServices.Models;
namespace XamarinWebServices
{
public partial class DropDown : ContentPage
{
CustomerVM viewModel;
public DropDown()
{
InitializeComponent();
viewModel = new CustomerVM();
BindingContext = viewModel;
}
async override protected void OnAppearing()
{
base.OnAppearing();
var json = await GetCustomersAsync();
List<CustomerVM> customers = JsonConvert.DeserializeObject<List<CustomerVM>>(json);
foreach (CustomerVM c in customers)
{
if (c.Data != null)
{
string name = c.Data.name;
int ID = c.Data.id;
CustomerViewModel v = new CustomerViewModel();
v.name = name; v.id = ID;
CustomerList.Items.Add(name);
viewModel.CustomerList.Add(v);
}
}
}
async Task<string> GetCustomersAsync()
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://www.doctorksa.com/webservices/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("country");
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
return result;
}
else return response.ReasonPhrase;
}
void CustomerList_SelectIndexChanged(object sender, EventArgs args)
{
DisplayAlert("Test", "Ok", "Cancle", "Confirm");
}
}
}
Hope this will help you in working with dropdown and Web API