1
我工作在AspNetCore一個項目,EntityFrameworkCore,我想使用Ajax來得到一個對象,但我控制器不能以JSON序列正確這個對象,所以我的Ajax調用觸發錯誤而不是成功事件。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);
}
}
和我的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;
我希望有人可以幫助我,我真的沒有找到一個解決我的問題。
是的,謝謝你現在的工作。你還有一個想法,正確地解析我的JSON對象到我的腳本對象(所有屬性寫作不同) – Elykx
真的不知道,可能是這樣的:var myObject = response as TypeA; (完全猜測) –
mhh不工作,但謝謝我會嘗試自己找到它 – Elykx