如何在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
相关产品推荐
相关产品推荐

