无法在 Ajax 中使用导航属性(ASP NET CORE 6)

问题描述 投票:0回答:1

当我执行 Ajax get 请求时,服务器返回如下:

{
    "$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"
                        }
                    ]
                }
            }
}

我的问题是我可以访问颜色导航,这里是代码:

 <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。我还在方法中包含了颜色导航

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

我使用console.log(data)data 无论如何,我可以解决这个问题吗?尝试了很多方法还是不行

c# asp.net json asp.net-core asp.net-ajax
1个回答
0
投票

解决方案:将$.each函数中的data替换为data["$item"]

© www.soinside.com 2019 - 2024. All rights reserved.