当我执行 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>
public async Task<JsonResult> GetProductByColorAsync (int id)
{
var list = _context.ProductItems.Where(n => n.ProductId == id)
.Include(n => n.Color)
.ToList();
return Json(list);
}
解决方案:将$.each函数中的data替换为data["$item"]