Transmitting intricate information and handling JSON challenges in asp.net

I am attempting to send a complex data structure to my server-side method using jQuery.

Below is the C# class structure that I am working with:

public partial class SerializeJSON : System.Web.UI.Page
{

    [System.Web.Services.WebMethod]
    public static string GetData(List<Customer> oCust)
    {
        int empid = oCust[0].EmpID;
        string name = oCust[0].Name.ToString();
        DateTime dob = oCust[0].BirthDate;
        double sal = oCust[0].Salary;
        Address add = oCust[0].Address[0];
        return "";
    }
}

public class Customer
{
     List<Address> add = null;
     public Customer()
     {
         add = new List<Address>();
     }

    public int EmpID { get; set; }
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }

    public List<Address> Address
    {
        get { return add; }
        set { add = value; }
    }
    public double Salary { get; set; }
}

public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string PostCode { get; set; }
}

I have an idea of what the correct JSON format should look like. It would be as follows:

[
{
    "EmpID":1,
    "Name":"Keith",
    "BirthDate":"\/Date(947874600000)\/",
    "Address":[{"Address1":"Salt lake","Address2":"Kolkata","PostCode":"784512"}],"Salary":5200
}

Here is my approach for sending data from the client to the server side in JavaScript:

 var Person = {};
    Person["EmpID"] = 1;
    Person["Name"] = "Keith";
    Person["BirthDate"] = "08/15/2011";

    var Address = {};
    Address["Address1"] = "Salt lake";
    Address["Address2"] = "Kolkata";
    Address["PostCode"] = "741258";

    Person["Address"] = Address;

$(function () {
        $('#btnSubmit').click(function () {
            alert(JSON.stringify(Person));
            $.ajax({
                type: "POST",
                url: "SerializeJSON.aspx/GetData",
                data: "{'oCust':'" + JSON.stringify(Person) + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                }
                ,
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                }
            });
            return false;
        });
    });

However, I encountered an error where JSON.stringify() did not generate the correct JSON format. I am seeking guidance on the best way to programmatically populate and generate the right JSON data without manual intervention.

Please advise me on how to dynamically generate the correct JSON data using JavaScript for seamless deserialization at the server-side. Thank you.

I have restructured my code according to Naveen's suggestion:

var Persons = [];

var Person = {}; Person["EmpID"] = 1; Person["Name"] = "Keith"; Person["BirthDate"] = "08/15/2011";

var Address = []; var addr = {}; addr["Address1"] = "Salt lake"; addr["Address2"] = "Kolkata"; addr["PostCode"] = "741258"; Address.push(addr);

Person["Address"] = Address;
Persons.push(Person)

var DTO = { oCust : Persons } data: JSON.stringify( DTO )

I believe this revised approach will work. Do you agree?

If my class structure were modified as shown below:

public partial class SerializeJSON : System.Web.UI.Page {

    [System.Web.Services.WebMethod]
    public static string GetData(Customer oCust)
    {
        int empid = oCust.EmpID;
        string name = oCust.Name.ToString();
        DateTime dob = oCust.BirthDate;
        double sal = oCust.Salary;
        Address add = oCust.Address[0];
        return "";
    }
}

public class Customer
{
     List<Address> add = null;
     public Customer()
     {
         add = new List<Address>();
     }

    public int EmpID { get; set; }
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }

    public List<Address> Address
    {
        get { return add; }
        set { add = value; }
    }
    public double Salary { get; set; }
}

public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string PostCode { get; set; }
}

Then, the corresponding JSON format would be:

Answer №1

Learn how to automatically deserialize complex JSON using a WebMethod.
Make sure to read the comments for any clarifications.

Custom Classes

public class Customer
{
    public int EmpID { get; set; }
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }

    // Explanation on using conventional get/set methods
    public List<Address> Address { get; set; }
    public double Salary { get; set; }
}

public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string PostCode { get; set; }
}

Implementation in WebMethod

[System.Web.Services.WebMethod]
public static string GetData(Customer oCust)
{
    try
    {
        int empid = oCust.EmpID;
        string name = oCust.Name.ToString();
        DateTime dob = oCust.BirthDate;
        double sal = oCust.Salary;
        Address add = oCust.Address[0];
        return "Success";
    }
    catch (Exception exception)
    {
        //Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
        return "Failed";
    }
}

AJAX Call Setup

$(function () {
    $('#btnSubmit').click(function (evt) {
        var Person = {};
        Person["EmpID"] = 1;
        Person["Name"] = "Keith";
        //Converting to date is optional but increases type safety
        Person["BirthDate"] = new Date("08/15/2011");

        var Address = [];
        var addr = {};
        addr["Address1"] = "Salt lake";
        addr["Address2"] = "Kolkata";
        addr["PostCode"] = "741258";
        Address.push(addr);

        Person["Address"] = Address;

        var DTO = { oCust: Person }
        
        $.ajax({
            type: "POST",
            url: "SerializeJSON.aspx/GetData",
            data: JSON.stringify(DTO),
            contentType: "application/json",
            success: function (msg) {
                var data = msg.hasOwnProperty("d") ? msg.d : msg;
                $("#content").hide().html(msg.d).delay(1000).show(400);
            },
            error: function (xhr, textStatus, errorThrown) {
                alert(xhr.responseText);
            }
        });
        evt.preventDefault();
    });
});

HTML Elements

<div id="content"></div>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"/>

Feel free to reach out if you have any questions or need further assistance!

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

Is Moment.js displaying time incorrectly?

When using moment.tz to convert a specific date and time to UTC while considering the Europe/London timezone, there seems to be an issue. For example: moment.tz('2017-03-26T01:00:00', 'Europe/London').utc().format('YYYY-MM-DD[T]HH: ...

How can I establish a breakpoint on an HTML element?

For instance, I have a button element with the click event attached to an ID in XXX.js file (the actual file name is unknown), and there are several .js files in the project. How can I debug the button click if I don't know where the function for it i ...

Issues with password confirmation function in Vuetify components

I am struggling to create a registration form where users must confirm their password by typing it in twice, but I can't seem to get Vuetify to validate that the two passwords match. Despite trying to set up rules for this validation, my code doesn&a ...

Next JS is trying to access a JSON file that does not exist

After setting up a route "/es/servicios" and configuring it in next.config.js: module.exports = { async redirects() { return [ { source: '/', destination: '/es', ...

Using JavaScript to sort through an array of nested objects

I'm working on extracting data from a deeply nested array. Here's the initial setup: layout: { parent: [ { type: "tabset", id: "tab1", children: [ { type: "tab", id: "id1& ...

What is the best way to dynamically search and retrieve data from a JSON object in Angular?

I am facing a challenge with my Angular (v. 1.6.3) app where I have fetched a JSON object containing stock price data. The structure of the JSON object only allows querying using brackets, with each key being a string that may include spaces, parentheses, ...

Tips on efficiently storing JSON objects into an array using PHP

Below is my PHP code used to retrieve data in JSON format: if($status==1) { $post_id=$json_object['post_id']; $get_postid=mysqli_query($con,"select * from User_Post where post_id='$post_id'"); if(mysqli_nu ...

Anticipated the start of an array, but encountered the start of an object at line 1, position 2

I'm currently developing an app that requires sending notifications to specific devices, but I've encountered an error. I'm actively searching for a solution and utilizing the REST API endpoint . It's been a challenge, but I'm dete ...

Having trouble importing XML data from an external file with jQuery

Attempting to import external XML with the code below is proving unsuccessful $( document ).load( "data.xml", function( response, status, xhr ) { console.log( xhr.status + " " + xhr.statusText ); }); Both data.xml and js files are in the ...

How can default props be set for a nested object in Vue?

Here's how I've defined my props: myHouse = { kitchen:{ sink: '' } } I attempted to set the default props like this, but it didn't work as expected. props: { house: { type: Object, default: () => { ...

Storing multiple email addresses in an array using an HTML input element

I have a small React Bootstrap form where I am trying to save multiple email addresses entered by the user into an array. However, when I use onChange={()=> setEmails(e.target.value as any} it stores them in string format like this --> [email p ...

Python program that runs a loop through a file, sends API requests using the `requests` library, and saves the results

Currently working on a program to loop through movie titles in a text file and make API calls to store the responses. The text file contains a single title on each line, for example: Titanic Avatar A Star Is Born The API being used is from a website ca ...

How can I retrieve the $index value of an ng-repeat element within a uib-dropdown?

I am currently working on implementing an ng-repeat loop that includes a dropdown menu for each element. I want the dropdown menu to contain functions that operate on the specific element, requiring access to the index of that element. Below is the code sn ...

Tips for locating the index of the previously selected active class

I am currently working on a slider and have made progress up to this point. However, I am facing an issue where I cannot proceed because I need to identify the index of the item from which I removed the last active class before the click event occurs. My ...

The function that triggers an image slide event in Bootstrap 4 carousel

Currently, I have implemented a bootstrap 4 carousel with 11 slides that are functioning as intended. I now have another div (#div-info) where I would like to display specific text and images based on the active carousel slide. For example, when slide 2 is ...

React powered interactive tables

I am in the process of creating a dynamic table using React, and here is the data structure I am working with: { numRows: 2, numCols: 3, cells: [ { id: 1, pos: { row: 1, col: 1 }, content: 'This is th ...

Creating separate chunks for individual files in Vue CLI3JsonPropertyTitleFileType

I am working on a project using vue-cli3 and need to separate out a specific file for chunking due to IIS requirements. Currently, webpack chunks files based on default settings and also automatically creates chunks from dynamic imports in vue-router. How ...

Combining two arrays of objects with unique properties into one

Two arrays of objects are given: array1 = [{"id":1,"cost":200,"qty":56},{"id":2,"cost":100,"qty":16}]; array2 = [{"id":1,"cost":200,"desc":"a good one"},{"id":2,"cost":100,"desc":"a bad one"},{"id":3,"cost":50,"desc":"an okay one"}]; The goal ...

How to eliminate the comma from the final element in a JavaScript Vue.js array?

I'm looking to remove the comma from the last element in Vue, but I'm unsure how to do so since the index of the last element is unknown. <td v-if="category.sub_category.length > 0"> <template v-for=&q ...

Framework7 disables the jQuery.appear plugin

I am utilizing Framework7 and aiming to incorporate jQuery.appear for executing a script once an element becomes visible to the user. The implementation is successful when using this code in a basic HTML setup: <!DOCTYPE html> <html> < ...