Home > OS >  Display details of `ItemKey` in a row from the JSON response
Display details of `ItemKey` in a row from the JSON response

Time:11-13

I have a table, Item, which stores key/value pairs. So my JSON returns key-value pairs. Key can be of three types: 'Item Name', 'Location', and 'Date'.

Model:

public class Item
{
    public Guid Id { get; set; }
    public string ItemKey { get; set; }
    public string Key { get; set; } // Key can be of three types `'Item Name', 'Location', 'Date'`
    public string Value { get; set; }       
}

How do I display all info of ItemKey on to one row, from the JSON? Grouping by ItemKey.

[
  {"id":"1","itemKey":"item1","key":"ItemName","value":"Apple"},
  {"id":"2","itemKey":"item2","key":"ItemName","value":"Orange"}, 
  {"id":"3","itemKey":"item1","key":"Location","value":"USA"},
  {"id":"4","itemKey":"item2","key":"Location","value":"Angola"},  
  {"id":"5","itemKey":"item2","key":"Date","value":"03.11.2022"}, 
  {"id":"6","itemKey":"item3","key":"ItemName","value":"Banana"},
  {"id":"7","itemKey":"item3","key":"Date","value":"24.10.2022"}
]

I would like to display each itemKey detail in the razor page as below:

For eg: Grouping by item1 would return:

itemKey - Item1, itemName - Apple, Location -USA (date is not available for item1)

<thead>
    <tr>
    <th>ItemKey</th>     
    <th>ItemName</th>
    <th>Location</th>
    <th>Date</th>    
    </tr>
</thead>

The current code is below for reference:

Below gets me list of items from the JSON

ItemService.cs:

public async Task<List<FecMetaDatum>> GetItems()
{
    return await _httpClient.GetFromJsonAsync<List<Item>>("api/Item");
}

Index.razor:

@foreach (var r in items)
{         
    <tr>
        <td>@r.id</td>     
        <td>@r.itemKey</td>
        <td>@r.key</td>
        <td>@r.value</td>    
    </tr>
}
   
protected override async Task OnInitializedAsync()
{
    items= await ItemService.GetItems();
}

CodePudding user response:

Since you know that the response will return either of three different keys for the key property. You need to Blazor table json

  • Related