Sending an array of numbers from JavaScript (using Ajax) to C# - a step-by-step guide

Normally, my typical AJAX call to pass an integer ID to the server side in C# would look like this:

 $.ajax({
            url: '@Url.Action("PlantHistoryContent", "PlantStatus")',
            data: {id: 1},
            async: false,
            type: "POST"
        })

However, what if I want to pass a list of integers?

Let's say I have an object-list of unknown length and I need to send it as a list to the server side. The corresponding server side method would be:

public void PlantHistoryContent(List<int> id)
{
 ///
}

How should I modify the data parameter in my AJAX call to accommodate this new requirement?

Answer №1

In JavaScript, a list can be created as follows:

var list = [ 1, 2, 3, 4 ];

You can also build the list step by step like this:

var list = [];
list.push(1);
list.push(2);
list.push(3);
list.push(4);

When sending the list using AJAX, you have two options:

$.ajax({
    url: '@Url.Action("PlantHistoryContent", "PlantStatus")',
    data: { ids: list },
    async: false,
    type: "POST"
})

or

$.ajax({
    url: '@Url.Action("PlantHistoryContent", "PlantStatus")',
    data: { ids: [ 1, 2, 3, 4 ] },
    async: false,
    type: "POST"
})

By default, form-encoding is used which converts all parameters into strings.

However, if you use JSON for encoding, you can send integers and maintain their types:

$.ajax({
    url: '@Url.Action("PlantHistoryContent", "PlantStatus")',
    data: { data: JSON.stringify({ ids: [ 1, 2, 3, 4 ] }) },
    async: false,
    type: "POST"
})

With JSON encoding, your request body will look like this:

data=%5B1%2C2%2C3%2C4%5D

Answer №2

For anyone facing a similar issue: If you are still struggling to find a solution, I encountered the same problem but found a fix: simply include [FromBody] in the controller action

public void GetPlantDetails([FromBody]List<int> plantIds)
{
    //
}

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

Tips for presenting the retrieved data from the database in a user-friendly format

$ //First step involves running the PHP code that executes the SQL query to retrieve data from the database, storing it in get_row1, and sending it as a response to Ajax$ <?php $connect = mysql_connect("localhost", "root", ""); $data = mysq ...

I am trying to move to a different page, but for some reason the router.navigate function is not functioning within the subscribe

//I am attempting to redirect to another page once the subscribe method is executed, however I am encountering issues with the router.navigate function within the subscribe method. //In an effort to address this issue, I have attempted to store the data r ...

Adding functions to the window scroll event

Rather than constantly invoking the handler, John Resig proposes using setInterval() to optimize the number of times it is called - check out his thoughts at http://ejohn.org/blog/learning-from-twitter/ In his blog post, John presents the following soluti ...

Ways to determine if an object is either undefined or null

I'm facing an issue that keeps resurfacing, but I can't seem to find a solution for it. In my project, I have 5 divs and I want to hide the div that was previously clicked on. For example, if the user clicks on div 1 and then on div 2, div 1 sho ...

Can the values in all fields of a JSON be combined or subtracted with those of another object containing the same fields?

I am currently working with a Mongoose.js schema that is structured as follows: { "City": String, "Year": String, "Population": Number, "Blah": Number, "Nested": { "Something": Number, "More stuff": Number } } Is there an efficient w ...

using app.use to directly pass arguments without delay (NODE.JS)

I'm currently figuring out why the code 1 is functioning properly, while the code 2 is not... app.js: // Implementing Routes var server = require('./routes/server'); app.use('/', server); Route.js: var express = require(&a ...

The error message "Error: cannot read property ‘setDirtyAttribute’ of null" may be encountered when attempting to use the method YourModel.create({...}) in ember-typescript-cli

Encountering the error cannot read property 'setDirtyAttribute' of null even when using YourModel.create({...}) in ember-typescript-cli to instantiate an EmberObject. Model: import DS from 'ember-data'; import {computed} from "@ember/ ...

What is the method for calling a function in a JavaScript file?

I am facing a challenge with reinitializing a JavaScript file named AppForm.js after a successful ajax post response. Within the file, there are various components: (function(namespace, $) { "use strict"; var AppForm = function() { // Cr ...

Having trouble with the onClick function in React?

Here is my simple react code: Main.js: var ReactDom = require('react-dom'); var Main = React.createClass({ render: function(){ return( <div> <a onClick={alert("hello world")} >hello</a> </ ...

Verifying in PHP if the request is intended for a JavaScript worker

After doing my research on MDN for the referrer-policy, as well as searching through Google, DuckDuckGo and Stack Overflow, I still find myself stuck on a seemingly simple yet elusive issue. Journey of Data the browser sends a request to the server the ...

What is the reason for the failure of the jQuery code to disable the submit button in the following snippet?

I am working on a feature to disable the submit button in a form when the username, email, password fields are empty. When all of them are filled, I want to enable the submit button. However, the current code is not disabling the submit button as expected. ...

What is the best way to transfer a request parameter from a URL to a function that generates an object with matching name in JavaScript?

I need to figure out how to pass a request parameter from an express router request to a function that should return an object with the same name. The issue I'm facing is that the function is returning the parameter name instead of the object. Upon c ...

Routing with nested modules in Angular 2 can be achieved by using the same

Encountering a common issue within a backend application. Various resources can be accessed through the following routes: reports/view/:id campains/view/:id suts/view/:id certifications/view/:id Note that all routes end with the same part: /view/:id. ...

Tips for formatting result data when using FullCalendar's eventSources URL

I am looking to retrieve my event data for fullcalendar from a separate URL. I have been following the method mentioned here: https://fullcalendar.io/docs/eventSources $('#calendar').fullCalendar({ eventSources: [ '/feed1.php' ...

Into the depths we delve, extending beyond to an array of objects?

I have a question about the possibility of extending an array of objects like this: Imagine I have : myObj = [ {"name" : "one", "test" : ["1","2"]}, {"name" : "two", "test" : ["1","2"]} ] And I want to add to it something like - {"name" : ...

Getting the most out of geometry vertices with Threejs: mastering partial transforms

In my current project, I am working with a mesh that consists of approximately 5k vertices. These vertices have been merged from multiple geometries into a flat array. Initially, I was able to modify individual vertices successfully by setting the flag `ve ...

Using Laravel Livewire to make text vanish by setting a time limit for the flash message

I've developed a feature using Laravel Livewire that triggers a modal to show up whenever a user successfully subscribes or volunteers to join my website. I attempted to implement code that would delay the modal, but instead of making text disappear a ...

Tips for ensuring that an Ajax request successfully executes when a page loads

I have a question about implementing an AJAX request in my code. Currently, I have the text on the screen updating when a dropdown input is selected using 'onchange'. However, I also want this same behavior to occur on page load, but I am struggl ...

Having several contact forms embedded within a single webpage

I am currently in the process of developing a prototype website and my objective is to have multiple forms on a single page. My goal is to have a form for each service, where users can click on the service and fill out a form to request a quote. The first ...

What is the most effective method for establishing a notification system?

My PHP-based CMS includes internal messaging functionality. While currently I can receive notifications for new messages upon page refresh, I am looking to implement real-time notifications similar to those on Facebook. What would be the most efficient ap ...