Sending multiple objects through an Ajax POST request to a WebApi 2 endpoint

I am encountering an issue with passing JavaScript array objects through ajax post to my web API 2. Below is the code snippet where I am experiencing a null value in my web API:

 <script>
    $(document).ready(function () {
        var Contacts = { steve: {},bill: {}, RON: {}, dan: {}, };
        Contacts.bill = { Name: "Bill", UserName: "Gates", MobileNUmber: "(206) 555-5555",};
        Contacts.steve = { Name: "Steve", UserName: "Jobs", MobileNUmber: "(408) 555-1111",};
        Contacts.jon = { Name: "Steve", UserName: "Jobs", MobileNUmber: "(408) 555-2222", };
        Contacts.RON = { Name: "Steve", UserName: "Jobs", MobileNUmber: "(408) 333-5555", };
        Contacts.dan = { Name: "Steve", UserName: "Jobs", MobileNUmber: "(408) 444-5555",};
        Contacts.qwe = { Name: "Steve", UserName: "Jobs", MobileNUmber: "(408) 555-5555",};
        var ContactList = JSON.stringify(Contacts);
        console.log(ContactList);
        var baseUrl = "http://localhost:55942/";

        $.ajax({
            type: "POST",
            data: ContactList,
            url: baseUrl + 'api/CONTACT/comparecontacts',
            contentType: "application/json"
        });
    });
</script> 

// In my WEB API, I noticed that I am receiving Null value in my Contact list //

    public class CONTACTController : ApiController
   {
        [HttpPost]
        public IHttpActionResult comparecontacts(List<ContactList> ContactList)
        {
            return Ok();
        }
    }

Answer №1

Instead of sending an array of contacts, you are actually sending an object with property names for each contact. To correct this issue, update your JavaScript code as follows:

$(document).ready(function () {
    var contacts = [];
    contacts.push({ Name: "Bill", UserName: "Gates", MobileNumber: "(206) 555-5555", });
    contacts.push({ Name: "Steve", UserName: "Jobs", MobileNumber: "(408) 555-1111", });

    //..

    var baseUrl = "http://localhost:55942/";
    $.ajax({
        type: "POST",
        data: JSON.stringify(contacts),
        url: baseUrl + 'api/CONTACT/comparecontacts',
        contentType: "application/json"
    });
});

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

Spotting the Visible Element; Detecting the Element in

Currently, my webpage has a fixed header and I am facing the challenge of dynamically changing the styling of the li elements within the navigation based on the user's scrolling position. To achieve this, I believe the most effective approach would b ...

javascript detect when two div elements are overlapping

On my webpage, I have implemented the effect.shrink() function. However, when clicking quickly on the page, the div tags start overlapping with other elements. What is the best way to solve this issue? I am using both scriptaculous.js and prototype.js fo ...

Accessing JSON object with Javascript

I've been struggling with this code snippet and despite looking at similar posts, I can't seem to get it right. var obj2 = JSON.parse('{"venue_data": {"venue_id":"25", "description":"Space Cafe", "venue_type ...

Is it possible to retrieve a class's array of properties without creating an instance of it?

It appears that there might be a way to accomplish this task by dynamically constructing a form based on a class definition (Angular) without being dependent on the specific class itself. This approach would allow for scalability, enabling the addition of ...

What is the best way to verify if a class attribute includes a specific class or not?

Below is the code snippet provided. The code fetches all classes and then checks for the presence of the 'mat-checked' class. pmanage.no_additional_cost().last().invoke('prop', 'class').then((Class) => { let ...

Enhancing Game Features, Streamlining In-App Calls, and Progress Bar Optimization

I'm trying to develop a Facebook game and implement a feature commonly seen in many other Facebook games (a function that calls my website and includes an illusionary image of a loading bar). The functionality I need is as follows: User clicks on ...

Issue encountered while attempting to parse JSON data

I've been dealing with JSON data in Django view and parsing it in JavaScript to extract the necessary information. This is a snippet from my view.py file (Django) ibms = [] for i in range(2, 5): ibm = Mapa(i, wsMapa) ibms.append(ibm.__dict__) ...

Displaying XML data with javascript is not possible when it is parsed

I am currently working on extracting data from an XML tree retrieved from an online RSS feed. However, when I attempt to place this data within a loop, it fails to display. Within a standard HTML file, my goal is to dynamically add this data to a table us ...

Getting the search API functioning in react-sortable-tree

My code includes a searchQuery prop as per the API documentation, however, the search functionality does not seem to be working properly. I have found that the API doc lacks clear instructions on how to implement the search feature, and the examples avail ...

What is the best method for changing the value of a DOM element depending on the status of another element?

Imagine implementing a text field that triggers the following code on each keydown event: if( $('#my_input').val() == '' ) $('#my_span').html('my input is blank'); else $('#my_span').html('My inpu ...

What steps can be taken to empower users to make changes to pre-selected data within the vue-select component?

Usage of vue-select component: Currently, I am looking for a way to enable my users to edit data that has already been selected. After going through the documentation, I couldn't find a direct method to achieve this. If anyone has experience working ...

Automatically generated error notifications for Express-Validator

I am looking to implement an Express API and incorporate request input validation using express-validator. Here is my current validation middleware: protected validate = async (request: Request, response: Response, next: NextFunction): Promise<void> ...

Is there an easier method to assign text to a modal-body using a specific classname?

Utilizing Bootstrap 5.1.3 alongside Pure Vanilla JavaScript, I have successfully been able to populate the .modal-body with content using the following code: function showBSModal(modalid, inputid) { var myModal = new bootstrap.Modal(document.getElement ...

Upon triggering an ajax post request, the HTML elements do not refresh as expected within an Angular environment

I am facing an issue where I make an AJAX POST request and it executes properly. After receiving the response, I need to make another AJAX GET request and assign the data to variables in the scope. The data is successfully assigned to the variables, but th ...

The Maginific popup feature appears to be malfunctioning

I'm currently working on a website and I've encountered an issue. After clicking on the search icon, a search window should open as shown in this image, but I'm getting an error in the console: index.php:113 Uncaught TypeError: $(...).magnif ...

Exploring Angular $resource with a playful twist

Is there a recommended method for mocking the $resource object? I've looked online, but all my attempts ended with KARMA testing. It's not what I'm looking for. I'm thinking of creating a fake object so that I can easily switch betwee ...

Tips for picking out a particular item from a list of child elements

When I select the first parent's children array, it ends up selecting every other parent's children as well. This is due to index 0 remaining the same for all of them. How can I specify and highlight a specific child? Link: Check out the stackb ...

Guide on implementing enums (or const) in VueJS

Seeking help on a seemingly simple task, I am trying to understand how to use "enums" in VueJS. In my file named LandingPage.js, I have the following code: const Form = { LOGIN: 0, SIGN_UP: 1, FORGOT_PASSWORD: 2, }; function main() { new Vue({ ...

Trouble arises when implementing AJAX in conjunction with PHP!

I am facing an issue with my PHP page which collects mp3 links from downloads.nl. The results are converted to XML and display correctly. However, the problem arises when trying to access this XML data using ajax. Both the files are on the same domain, b ...

What steps can be taken to receive an alternative result when selecting a checkbox?

Currently, I am tackling the issue with checkboxes in Vuetify. The challenge lies in achieving a different output for the second {{ selected.join() }}. For example, when I select the checkbox labeled "Social Media," I receive the text "On our social medi ...