I am currently tackling a project in AspNetCore involving EntityFrameworkCore and I am looking to utilize Ajax to retrieve an object. However, my controller is encountering issues when trying to serialize this object into Json format, causing my Ajax call to trigger an error instead of a successful event.
Below is my controller along with a test JsonConvert that is returning null:
[HttpGet]
public async Task<IActionResult> GetPackWithAllCards(int? packId)
{
if (packId == null)
{
return Json("An error has occurred");
}
else
{
var pack = await _context.Packs
.Include(p => p.TagPacks)
.ThenInclude(tp => tp.Tag)
// Additional includes omitted for brevity
.SingleOrDefaultAsync(m => m.PackId == packId);
if (pack == null)
{
return Json("An error has occurred");
}
var a = JsonConvert.SerializeObject(pack);
return Ok(pack);
}
}
Additionally, here is my ajax call using a 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("success:" + response.packId);
},
error: function (response) {
$.extend(pack, response);
alert("error:" + response);
}
});
alert(pack);
return pack;
If anyone could assist me with finding a solution to this issue, it would be greatly appreciated as I am currently stuck.