0

How to fill this list protected List<ItemModel> ItemList = new List<ItemModel>(); with data json from API in blazor

This is the Json data

[
    {
        "id":1,
        "itemName":"ROUTER MI C3",
        "idItemBrand":1,
        "idItemGroup":1,
        "dateCreated":"2019-12-26T00:00:00",
        "dateModified":"2019-12-26T00:00:00",
        "idUserModified":"1"
    }
]

this is the complete code

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Inventory.General;
using Inventory.Model.Master;
using Inventory.Client.Components.Base;
using Microsoft.AspNetCore.Components;

namespace Inventory.Client.Components.Master
{
    public class MasterDataBase : InventoryComponentBase
    {
        protected string error { get; set; }
        protected bool TableItem { get; set; } = true;
        protected bool TableItemBrand { get; set; } = false;
        protected bool TableItemGroup { get; set; } = false;
        protected int BtnTable { get; set; } = 0;
        protected List<ItemModel> ItemList = new List<ItemModel>();

        protected override async Task OnInitializedAsync()
        {
            GetDataItem();
        }

        protected async Task GetDataItem()
        {
            try
            {
                ItemList = await Http.GetJsonAsync<ItemModel>("api/inventory/v1/item");
            }
            catch (Exception ex)
            {

                error = ex.Message;
            }
        }
    }
}

This is the ItemModel Class

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;

namespace Inventory.Model.Master
{
    public class ItemModel
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public string ItemName { get; set; }
        public int IdItemBrand { get; set; }
        public int IdItemGroup { get; set; }
        public DateTime DateCreated { get; set; }
        public DateTime DateModified { get; set; }
        public string IdUserModified { get; set; }
    }
}
Jack J Jun
  • 5,633
  • 1
  • 9
  • 27
Bazara
  • 11
  • 4

1 Answers1

0

According to json structure, it is array of objects, so you need to parse it to collection, not to single item:

ItemList = await Http.GetJsonAsync<List<ItemModel>>("api/inventory/v1/item");
Roman.Pavelko
  • 1,555
  • 2
  • 15
  • 18