2017-06-01 3 views
1

AspNetCoreでEntityFrameworkCoreを使用しているプロジェクトで作業していますが、Ajaxを使用してオブジェクトを取得したいのですが、コントローラがJsonでこのオブジェクトを正しくシリアル化できないため、成功イベントの代わりにエラーをトリガーします。AspNetCore EntityModelがJsonにシリアル化できません

ここで私のコントローラ+テスト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; 

、私は本当に私の問題への解決策を見つけることができません。

答えて

2

私はこれを行う:

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

あなたは、コントローラでpackId値を取得していますか?

data: {packId : packId}, 
+0

はい、ありがとうございます。また、私のjsonオブジェクトを正しく私のtypescriptオブジェクト(すべてのプロパティが異なって書かれている)に解析するアイデアを持っています – Elykx

+0

本当によく分からない、多分何かのような:var myObject = Response as TypeA; (完全な推測) –

+0

mhhは働いていませんが、ありがとう私はそれを自分で見つけようとします – Elykx

関連する問題