Serialization of AspNetCore EntityModel to Json is not possible

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.

Answer №1

This is how I accomplish it:

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

Have you ensured that the packId value is being retrieved in the controller? You might need to utilize the following code:

data: {packId : packId},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Javascript to create a new regular expression, we can now read patterns in from

I am currently working on developing a bbcode filtering solution that is compatible with both PHP and JavaScript. Primarily focusing on the JavaScript aspect at the moment, I have encountered an issue with the new RegExp constructor not recognizing pattern ...

In React TypeScript, the property types of 'type' are not compatible with each other

I have a unique custom button code block here: export enum ButtonTypes { 'button', 'submit', 'reset', undefined, } type CustomButtonProps = { type: ButtonTypes; }; const CustomButton: React.FC<CustomButtonProp ...

What is the method for accessing an anonymous function within a JavaScript Object?

Currently facing an issue with a Node.js package called Telegraf, which is a bot framework. The problem arises when trying to create typings for it in TypeScript. The package exports the following: module.exports = Object.assign(Telegraf, { Composer, ...

Declaring a function type with a void parameter type in typescript

Embarking on my journey with ts and currently exploring TypeGraphQL. I came across something that caught my attention and seems unfamiliar to me: export declare type ReturnTypeFunc = (returns?: void) => ReturnTypeFuncValue; How should this type be unde ...

Storing toggle values (on/off) in a PHP database for future reference

I'm trying to use toggle buttons to save responses in a database as 'yes' or 'no'. However, for some reason the only response I am receiving is 'on', even when I switch off the button. I've searched for solutions but ...

Error: The REST Template in a Spring Boot application encountered a JsonParseException due to an invalid starting byte of 0x91

This specific query has been commonly raised on Stackoverflow but a solution for my unique scenario couldn't be located. In most cases, it's advised to save the JSON data in UTF-8 to ensure the caller receives a valid JSON response. However, in ...

Develop an enhancement for the Date object in Angular 2 using Typescript

Using the built-in Date type, I can easily call date.getDate(), date.getMonth()...etc. However, I am looking for a way to create a custom function like date.myCustomFunctionToGetMonthInString(date) that would return the month in a string format such as &a ...

What is the best way to elucidate this concept within the realm of TypeScript?

While diving into my ts learning journey, I came across this interesting code snippet: export const Field:<T> (x:T) => T; I'm having trouble wrapping my head around it. It resembles the function definition below: type myFunction<T> = ...

What is the best way to add JSON data to Payloads for API deployment?

Struggling to successfully insert JSON file contents inside {} for Payload. Any suggestions? Tried writing JSON file contents as a string without success. Also attempted to insert JSON file into payload = {}, but failed. import requests, meraki, json, os ...

fetch fresh content through ajax call

As a beginner in ajax, I am curious to know if it's possible to load an entire new page instead of just loading a part of it using ajax. Could you provide a small example script demonstrating whether this is feasible? My goal is to only show one URL t ...

Enabling JSON Support for WebAPI on Windows Server 2012 with IIS 8

I am experiencing an issue with my .Net webapi application on our IIS8 server. It works perfectly on my development machine, but once deployed, it fails to run when trying to return data in JSON format. Instead of receiving the expected JSON response, I am ...

Pressing the button triggers a client-side click event that activates an

Within my asp.net application, I have a button that has been defined in the following manner: Asp.net <asp:Button ID="TrackHistoryButton" runat="server" Text="Get Sensor History" CssClass="btn btn-default" ValidationGroup="HistoryDateValidationGroup" ...

Encountered an issue when attempting to save data to the database using an AJAX request in Symfony 3

i need to input text in a form and store it in my database as well as display it on my view using jQuery. here is the input form: <div class="panel rounded shadow"> <form method="post"> <textarea id="txt" class="form-control in ...

Is it possible to view all HTTP Get requests made by a browser without using any debugging tools?

I'm currently working on a page that uses various ajax and jsonp requests to fetch data. I am interested in finding out how to determine the request URL without relying on debugging tools such as firebug. Basically, I want to access the history of the ...

Customizing the HTMLElement class to modify particular attributes

Is there a way to modify the behavior of an HTMLElement's scrollTop property by adding some extra logic before updating the actual value? The common approach seems to be deleting the original property and using Object.defineProperty(): delete element. ...

Two jQuery functions within a single script

Having trouble defining multiple jquery functions within the same <script> tag. My script is not working as expected, but when I tested the ajax function separately, it worked perfectly. <script> $(function () { function loadLis ...

Handling invalid JSON data using JavaScript

Looking to extract data from this URL using Javascript. Here is a sample of the JSON content: {"ss":[["Thu","7:00","Final",,"BAL","19","ATL","20",,,"56808",,"PRE4","2015"],["Thu","7:00","Final",,"NO","10","GB","38",,,"56809",,"PRE4","2015"]]} Most tutori ...

Trouble with Fetching JSON Data using AJAX

Having trouble retrieving JSON data from an acronym finder API using a simple GET request. Here is the code I'm using: $.ajax('http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=DOD', { crossDomain:true, dataType: "jsonp ...

What is the best method for converting a modified array back to JSON format?

I'm currently working on a Discord bot that allows users to use the command tcp freeitem to receive a free item. My goal is to update the Account object by adding a new item to the account. However, when I attempt to map the array to replace a value, ...

Tips for setting discrete mapper style in cytoscapejs?

Currently, I am defining the style of cytoscape.js through CSS and converting it to JSON format using this resource. My goal is to implement a discrete mapper for styling. It's similar to the scenario discussed in How to use a descreteMapper like on c ...