Cannot use navigation property in Ajax (ASP NET Core 6)

38 Views Asked by At

When I perform an Ajax get request, the server returns something like this :

{
    "$id": "1",
    "$values": [
        {
            "$id": "2",
            "productItemsId": 30,
            "productId": 1,
            "colorId": 1,
            "productCode": "AFWhite",
            "image1": "",
            "image2": null,
            "image3": null,
            "image4": null,
            "color": {
                "$id": "3",
                "colorId": 1,
                "colorName": "Red",
                "colorHex": "#fa0000",
                "productItems": {
                    "$id": "4",
                    "$values": [
                        {
                            "$ref": "2"
                        }
                    ]
                }
            }
}

My problem is I can access the color navigation, here the code :

<script>
     $(document).on('change', '.ddlProductItemsId', function () {
         GetProductByColor($(this));
     });

     function GetProductByColor(selectedProductDropdown) {
         var productId = $(selectedProductDropdown).val(); 
         var colorDropdown = $(selectedProductDropdown).closest('tr').find('select[id="colorId"]'); 

         $.ajax({
             url: '@Url.Action("GetProductByColor", "Invoice")',
             type: 'GET',
             data: { id: productId },
             success: function (data) {
                 $(colorDropdown).empty(); 
                 $.each(data, function (index, item) {
                     
                     $(colorDropdown).append('<option value="' + item.colorId + '">' + item.color.colorName + '</option>');
                 });
             }
         });
     }
</script>

The view is always blank the view. I also include Color Navigation in the method

public async Task<JsonResult> GetProductByColorAsync (int id)
{   
    var list = _context.ProductItems.Where(n => n.ProductId == id)
        .Include(n => n.Color)
        .ToList();
    return Json(list);    
}

When I use console.log(data), I get: data

Is there anyway that I can solve this problem? I have tried many ways but it still doesn't work

1

There are 1 best solutions below

0
John On

Solutions : Replace data with data["$item"] in the $.each function