You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6中Ajax无法访问导航属性的问题求助

ASP.NET Core 6中Ajax请求无法访问Color导航属性的问题

在ASP.NET Core 6项目中执行Ajax GET请求时,服务器返回如下格式的JSON:

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

问题描述

无法访问color导航属性,视图中颜色下拉框始终空白。相关代码如下:

前端代码

<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>

后端代码

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)能看到返回的数据,但下拉框仍无内容。


修复方案

方案1:前端处理JSON的$values包装

返回的JSON是EF Core循环引用序列化产生的格式,数组被包裹在$values字段中,需先取出实际数组再遍历:
修改Ajax的success回调:

success: function (data) {
    $(colorDropdown).empty(); 
    // 兼容标准数组和带$values的格式
    var productItems = data.$values || data;
    $.each(productItems, function (index, item) {
        $(colorDropdown).append('<option value="' + item.colorId + '">' + item.color.colorName + '</option>');
    });
}

方案2:后端修改序列化配置,禁用循环引用格式

在Program.cs中配置JSON序列化,忽略循环引用并生成标准JSON数组:

builder.Services.AddControllersWithViews()
    .AddJsonOptions(options =>
    {
        // 忽略循环引用,避免生成$id/$ref/$values
        options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
        // 可选:格式化输出JSON
        options.JsonSerializerOptions.WriteIndented = true;
    });

修改后后端返回的将是标准数组,前端无需额外处理$values。

方案3:确保后端方法与路由匹配

后端方法名为GetProductByColorAsync,但前端Url.Action调用的是GetProductByColor,需保持一致:

  • 要么给后端方法添加特性:[ActionName("GetProductByColor")]
  • 要么修改前端的Action名称为GetProductByColorAsync

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 04:17:09