AspNetCore EntityModel 无法序列化为 Json



我正在使用EntityFrameWorkCore在Aspnetcore中进行一个项目,我想使用Ajax来获取对象,但是我的控制器无法在JSON中正确序列化此对象,所以我的Ajax调用触发错误而不是成功事件。

这是我的控制器 test jsonconvert return null。

        [HttpGet]
        public async Task<IActionResult> GetPackWithAllCards(int? packId)
        {
            if (packId == null)
            {
                return Json("An error has occured");
            }
            else
            {
                var pack = await _context.Packs
                .Include(p => p.TagPacks)
                .ThenInclude(tp => tp.Tag)
                .Include(p => p.CardPacks)
                .ThenInclude(cp => cp.Card)
                .ThenInclude(c => c.FaceCards)
                .ThenInclude(fc => fc.Face)
                .ThenInclude(fc => fc.Template)
                .Include(p => p.CardPacks)
                .ThenInclude(cp => cp.Card.FaceCards)
                .ThenInclude(fc => fc.Face.Image)
                .Include(p => p.CardPacks)
                .ThenInclude(cp => cp.Card.FaceCards)
                .ThenInclude(fc => fc.Face.Sound)
                .SingleOrDefaultAsync(m => m.PackId == packId);
                //pack is correctly returned from database
                if (pack == null)
                {
                    return Json("An error has occured");
                }
                var a = JsonConvert.SerializeObject(pack);
                return Ok(pack);
            }
        }

和我的Ajax调用打字稿对象:

        var pack = new Pack(0, 0, 0, "", "", 0, 0, false, null, null);
        $.ajax({
            type: "GET",
            url: "/pack/GetPackWithAllCards",
            dataType: "text",
            data: {packId},
            async: false,
            success: function (response) {
                $.extend(pack, response);
                alert("succes:"+response.packId);
            },
            error: function (response) {
                $.extend(pack, response);
                alert("error:" + response);
            }
        });
        alert(pack);
        return pack;

我希望有人可以帮助我,我真的找不到解决我问题的解决方案。

我这样做:

return new ContentResult
            {
                Content = JsonConvert.SerializeObject(data, Formatting.None, new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}),
                ContentType = "application/json"
            };

您是否在控制器中获得包装值?您可能需要使用:

data: {packId : packId},

最新更新