Elykx
Elykx

Reputation: 217

AspNetCore EntityModel can't serialize to Json

I'm working on a project in AspNetCore with EntityFrameworkCore and i would like to use Ajax to get an object but my controller can't serialize this object correctly in Json, so my Ajax call trigger an error instead of a success event.

Here is my controller + test JsonConvert that 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);
            }
        }

and my ajax call with typescript object:

        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;

I hope someone could help me, i really don't find a solution to my problem.

Upvotes: 1

Views: 91

Answers (1)

Mark Redman
Mark Redman

Reputation: 24535

I do this:

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

Are you getting the packId value in the controller? you may need to use:

data: {packId : packId},

Upvotes: 2

Related Questions