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

如何在ASP.NET Core 6返回的JSON中访问导航属性的图片?

问题解决:JSON中productItems导航属性的正确访问方式

问题根源

你的代码报错是因为item.productItems["$values"]是数组类型,而非单个对象,直接调用.image1会因为数组没有这个属性返回undefined。从JSON结构可以看到,productItems.$values里包含多个productItem对象,每个对象才有image1属性。

正确访问方式

根据需求,分两种场景处理:

场景1:取第一个productItem的图片

如果只需要每个商品的第一张图,直接给数组加索引[0]即可:

$.each(productlist["$values"], function (index, item) {
    newproductrow += '<div class="col-md-4 col-xs-6">';
    newproductrow += '<div class="product">';
    newproductrow += '<div class="product-img">';
    // 访问数组第一个元素的image1
    newproductrow += '<img src="~/Contents/img/' + item.productItems["$values"][0].image1 + '" width="200" height="200" alt="">';
    // 剩余代码...
});

场景2:遍历所有productItems生成图片

如果需要展示当前商品的所有图片,要嵌套一个$.each循环遍历productItems.$values:

$.each(productlist["$values"], function (index, item) {
    newproductrow += '<div class="col-md-4 col-xs-6">';
    newproductrow += '<div class="product">';
    newproductrow += '<div class="product-img">';
    
    // 遍历当前商品的所有productItems
    $.each(item.productItems["$values"], function (imgIndex, imgItem) {
        newproductrow += '<img src="~/Contents/img/' + imgItem.image1 + '" width="200" height="200" alt="">';
    });
    
    // 剩余代码...
});

额外建议

为避免空值报错,可以先判断productItems.$values是否存在且不为空:

$.each(productlist["$values"], function (index, item) {
    newproductrow += '<div class="col-md-4 col-xs-6">';
    newproductrow += '<div class="product">';
    newproductrow += '<div class="product-img">';
    
    // 先做非空判断
    if (item.productItems?.["$values"]?.length > 0) {
        // 取第一个图片或遍历所有图片
        newproductrow += '<img src="~/Contents/img/' + item.productItems["$values"][0].image1 + '" width="200" height="200" alt="">';
    } else {
        // 没有图片时的占位内容
        newproductrow += '<div class="no-image">暂无图片</div>';
    }
    
    // 剩余代码...
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 20:21:07