Search code examples
c#entity-frameworkasp.net-corexamarin.formsmvvmcross

Xamarin How to load listView detail from Rest API based on id?


I have listview. when the item clicked, it will open detail page. But for performance issue, in restAPI I set it to only send the data needed on the listView. That's why I want to get new request to api based id which I have from clicked listview.

listview.xaml.cs:

        private async void OnItemSelected(object sender, ItemTappedEventArgs e)
        {
        var itemDetail = e.Item as Data.Models.ModelAttendance.Attendance;
        await Navigation.PushAsync(new ListDetailAttendPage
            (
                itemDetail.Id, itemDetail.Image, itemDetail.Created, itemDetail.AddressDetail,
                itemDetail.Note, itemDetail.Activity
            ));
        }

listViewDetail.xaml.cs

    private ObservableCollection<Data.Models.ModelAttendance.Attendance> _attendances;

    public ListDetailAttendPage (long id, byte[] image, DateTime created, string addressDetail, string note, string activity)
    {
        InitializeComponent ();

        long idItem = id;
        ImgSelfie.Source = ImageSource.FromStream(() => new MemoryStream(image));
        EntTime.Text = created.ToString();
        EdtLocation.Text = addressDetail;
        EntNote.Text = note;
        LblAction.Text = activity;

    }

    protected override void OnAppearing()
    {
        _attendances = new ObservableCollection<Data.Models.ModelAttendance.Attendance>();
        base.OnAppearing();
    }

the API code that i use in listview page:

    [HttpGet]
    public IActionResult GetM_ATTENDANCE()
    {
        var data = _context.M_ATTENDANCE.Select(f => new Attendance
        {
            Id = f.Id,
            Name = f.Name,
            Activity = f.Activity,
            Created = f.Created
        }).OrderByDescending(x => x.Id).ToList();

        var tempJson = new
        {
            Data = data,
            Size = data.Count
        };
        return Json(tempJson);
    }

How can I do that in xamarin.form ? I have searched but there is no right solution. This is what I have try, but I still can't get wanted data :

    private ObservableCollection<Data.Models.ModelAttendance.Attendance> _attendances;
    HttpClient client = new HttpClient();

    public ListDetailAttendPage (long id, byte[] image, DateTime created, string addressDetail, string note, string activity)
    {
        InitializeComponent ();

        long idItem = id;
        ImgSelfie.Source = ImageSource.FromStream(() => new MemoryStream(image));
        EntTime.Text = created.ToString();
        EdtLocation.Text = addressDetail;
        EntNote.Text = note;
        LblAction.Text = activity;

        Task.Run(async () =>
        {
            await GetItem(idItem);
        });

    }

    async Task GetItem(long id)
    {
        HttpResponseMessage message = await client.GetAsync(string.Format("http://[url]:[port]/api/attendances/" + id));
        string jsonString = await message.Content.ReadAsStringAsync();

     //what should I do next to get the data here?

    }

    protected override void OnAppearing()
    {
        _attendances = new ObservableCollection<Data.Models.ModelAttendance.Attendance>();
        base.OnAppearing();
    }

I already have rest API to get respons based on id, but dont know to use it in Xamarin :

        // GET: api/Attendances/5
    [HttpGet("{id}")]
    public async Task<IActionResult> GetAttendance(long id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var attendance = await _context.M_ATTENDANCE.FindAsync(id);

        if (attendance == null)
        {
            return NotFound();
        }

        return Ok(attendance);
    }

I just started learning xamarin, please ask me if my question is still not clear

your help is much appreciated ^_^


Solution

  • Just deserialize JSON string into the class Model

    using Newtonsoft.Json;
    
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
    
    
            testAsync();
        }
    
        public async Task testAsync() {
    
            string json = @"{
                  'id': '123',
                  'name': 'User name',
                  'nik': '213123'
                }";
    
            Model m = JsonConvert.DeserializeObject<Model>(json);
    
            Console.WriteLine(m.name);
            Console.WriteLine(m.nik);
    
        }
    }
    
    public class Model
    {
        public string id { get; set; }
        public string name { get; set; }
        public string nik { get; set; }
        public string Created { get; set; }
    }
    

    Update: update UI in Main thread

      Device.BeginInvokeOnMainThread(() => {
                    EdtLocation.Text = result.AddressDetail;
                    //...
                });