AspNetCore EntityModel无法序列化为Json

时间:2017-06-01 07:58:06

标签: json ajax typescript asp.net-core entity-framework-core

我正在使用EntityFrameworkCore在AspNetCore中开发一个项目,我想使用Ajax来获取一个对象,但是我的控制器无法在Json中正确地序列化这个对象,所以我的Ajax调用会触发错误而不是成功事件

这是我的控制器+测试JsonConvert返回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);
            }
        }

和我使用typescript对象调用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;

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

1 个答案:

答案 0 :(得分:2)

我这样做:

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

您是否在控制器中获得了packId值?你可能需要使用:

data: {packId : packId},