Utilizing JavaScript to extract information from a JSON object generated using Json.Net

I have a method on the server-side that retrieves user data from a SQL Server database using EF 6. The data is then serialized using the Json.NET framework and returned to the client without filtering out references to other tables, requiring me to use the "PreserveReferencesHandling" option.

On the client-side, AJAX is used to call this server-side method. However, I am facing difficulties extracting the data from the serialized object on the client-side even though it is delivered to the browser as expected.

Here is an excerpt of the server-side method:

[WebMethod]
public static string ContactData(long id)
{
    IService<Contact> contactService = new ContactService();
    Contact contactEdit = contactService.GetById(id);

    string str = JsonConvert.SerializeObject(contactEdit, new JsonSerializerSettings
    {
        PreserveReferencesHandling = PreserveReferencesHandling.Objects
    });

    return str;
}

And here is the relevant part of the client-side function:

$.ajax({
    type: "POST",
    url: "Contacts.aspx/ContactData",
    data: JSON.stringify({ id: contactId }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (contact) {
        $("#tbFirstName").val(contact.d[0].Contact.first_name);
    },
});

In Visual Studio's JSON Visualizer, the JSON object for testing purposes looks like this:

While in the browser (Firebug), the received JSON object appears like this: Firebug

If more information is required, please let me know.

Answer №1

Make sure to properly parse the json data before proceeding with any processing. Utilize the jQuery each function to loop through the data.

    $.ajax({
        type: "POST",
        url: "Contacts.aspx/ContactInfo",
        data: JSON.stringify({ contactId: id }), // use the correct id for receiving the object
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data)
                {
                    var contacts = jQuery.parseJSON(data);
                    $.each(contacts, function(index, item) {
                        alert(index + " ==> "+  item.name);
                    });

                 }

    });

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

Confirming the selected value in a dropdown menu

When a user fails to select a value from the dropdown labeled "Select City," I want a validation message to appear saying, "Please Select your City." I attempted the following approach but it did not work: [Required] public IEnumerable<LocationInforma ...

Exploring the process of extracting specific data from a dynamic JSON response and seamlessly transferring it to another request

After receiving a .json file as a response from an API, I need to parse it and extract a specific parameter to pass as input to the next request. How can this be accomplished using Katalon? When attempting to use: response = JSON.parse("response.json"); ...

Why is it impossible to nest schemas without using an array?

Can anyone explain why mongoose schema definitions don't allow something like this: var NameSchema = new mongoose.Schema({ first: {type: String, trim: true }, last: {type: String, trim: true } }); var UserSchema = new mongoose.Schema({ name: N ...

How can I configure AngularJS intellisense in Visual Studio Code?

I've been customizing Visual Studio Code for better compatibility with our Angular 1.5 codebase at my workplace. Here's the progress I've made so far: Downloaded and installed TSD Ran the command tsd query -r -o -a install angular -s Added ...

Creating a customized component using unique styles in Material UI version 1

Currently, I am facing a challenge in styling my Card component with a width of 75 pixels while using Redux and Material UI V1. Despite following the example provided by Material UI on custom styling through withStyles and connect, I have not been able to ...

PHP script automatically resets select option on page load

Consider the following scenario: <form name="limit"> <select name="limiter" onChange="limit(this.value)"> <option selected="selected">&nbsp;</option> <option value="5">5</option> <opti ...

Deciding between Document.createElement() and Document.createTextNode() in Javascript

I'm currently exploring the distinctions between these two code snippets: // first one var h1 = document.createElement('h1'); var t = document.createTextNode('hello'); h1.appendChild(t); document.body.appendChild(h1); // second o ...

Sending an array of objects in JavaScript to a controller

I have a dynamic form that I'm trying to submit to my Controller. Instead of sending just a string or an array with data, I need to pass an array of objects using ajax request after building the Javascript Array. The challenge is that when I send only ...

What is the process for instantiating an IList object?

When working in C#, it's commonly understood that one cannot create an instance of an interface: > new IList<double>() (1,1): error CS0144: Cannot create an instance of the abstract class or interface 'IList<double>' However ...

Quarterly Date Selection Tool with jQuery

I attempted to utilize the Quarter datepicker from: http://jsfiddle.net/4mwk0d5L/1/ Every time I execute the code, I encounter this problem: Cannot set property 'qtrs' of undefined. I copied exactly what was in the jsfiddle, and included the sam ...

Sending an Angular scope variable to JavaScript

I am working with an angular scope variable that is being used in ng-repeat. My goal is to create a chart that starts from a specific date, ends at another date, and includes a marker for the current day. I am utilizing loader.js for drawing the charts in ...

The use of DataTables to integrate nested child tables with another DataTables serverside

On a page, I have a master datatable and when a row is clicked, I want to display a child from a server-side datatable. The datatable code is correct, as it works in separate mode. This function is called when a row on the master table is double-clicked: ...

When using JavaScript to redirect with window.location, the referrer header is not properly set

Currently, I am attempting to utilize window.location in React to redirect to a third-party page. However, upon making the redirect, the third-party server is not receiving a referrer header from my redirection. Any assistance on resolving this issue wou ...

Creating custom outlines for CSS shapes

Exploring the world of CSS shapes has left me wondering - is it possible to give them solid, dotted, or dashed borders? I came across some examples of shapes that caught my eye (shapes), but making them stand out with different border styles posed a challe ...

Modify the color of a hotspot area when the mouse is hovered over it

I have a task of dynamically generating HotSpots on an Image Map control. Below is the code snippet that accomplishes this: // Creating a RectangleHotSpot programmatically. RectangleHotSpot Rectangle1 = new RectangleHotSpot(); Rectangle1.Top = 50; Rectang ...

Attention: Vanishing within specified time limit

Can you help me find a technology that will display a warning message and make it disappear with a nice effect over a set amount of time? I think AJAX or JavaScript might be able to achieve this. The warning message I'm currently using is: <scrip ...

Calculating the Distance Between Elements within a Flex Container Using JavaScript

I am looking to calculate the margin left and right for children of a flex item <div class="sec images" style="display:flex;justify-content:space-between"> <img src="images/en_mb-mega-01.png" alt=""> ...

Embed a three.js scene into a grid layout using Bootstrap

Trying to embed a three.js scene with toggle switches inside a Bootstrap grid. The issue is that my canvas, which is inside a column, doesn't align properly with the text column on the same row. Any assistance would be greatly appreciated. Preview: V ...

Error: The navigation property is not defined - React Native

Utilizing Firebase in combination with react-native for user authentication. The main file is App.js which directs users to the Login component and utilizes two components for managing routes: Appnavigator.js to create a switchNavigator and DrawerNavigator ...

embedding JSON data into the main template

I'm looking to include a JSON string by injecting some JavaScript on each page. In the master page, I have: public partial class TheMasterPage : System.Web.UI.MasterPage { protected void Page_Init(object sender, EventArgs e) { if (Session[ ...