Sending a JavaScript array to an MVC controller in .NET 5.0 via a POST request

Trying to send data from a JavaScript array to an MVC controller. While debugging, I end up in the method

public void GetJSArray(List<SelectorModel> selectorModels)

However, the selectorModels is currently showing as null.

Below is the model being used:

public class SelectorModel
    {
        public int ID { get; set; }
        public string Cords { get; set; }
        public string Name { get; set; }
    }

Here is the C# code in the controller:

 [HttpPost]
        public void GetJSArray(List<SelectorModel> selectorModels)
        {
            //Code here           
        }

And this is the JavaScript/Ajax function:

function SaveInfoSpots() {
    var savedeSpots = JSON.stringify({ selectorModels: infospots });
    $.ajax({
        type: "POST",
        url: '/Home/GetJSArray',
        contentType: "application/json; charset=utf-8",
        dataType: 'JSON',//json
        data: savedeSpots,
        traditional: true
    });
}

When making a console.log(savedeSpots), the following is displayed:

{"selectorModels":[{"ID":1,"Name":"InfoSpot1","Cords":"5000.00, 2293.85, 2278.05"},{"ID":1,"Name":"InfoSpot2","Cords":"1.94, 584.50, 5000.00"},{"ID":1,"Name":"InfoSpot3","Cords":"5000.00, -2705.97, -277.02"},{"ID":1,"Name":"InfoSpot4","Cords":"5000.00, 504.93, -2845.93"}]}

Answer №1

There are two key modifications needed in your code:

Firstly, regarding model binding, make sure to add the [FromBody] attribute on the action parameter like so:

[HttpPost]
public void GetJSArray([FromBody]List<SelectorModel> selectorModels)
{
    //Your code goes here           
}

Secondly, it's important to note that your API expects an array rather than an object. When calling the API, ensure you post the parameters in the following format:

[
    {
        "ID": 1,
        "Name": "Infospot1",
        "Cords": "5000.00, 2293.85, 2278.05"
    },
    {
        "ID": 1,
        "Name": "Infospot2",
        "Cords": "1.94, 584.50, 5000.00"
    },
    {
        "ID": 1,
        "Name": "Infospot3",
        "Cords": "5000.00, -2705.97, -277.02"
    },
    {
        "ID": 1,
        "Name": "Infospot4",
        "Cords": "5000.00, 504.93, -2845.93"
    }
]

Ensure you do not use the {"selectorModels":...} format.

If your main focus is on APIs, consider creating a webapi project instead of an mvc project for better efficiency.

Answer №2

Make sure to include the [FromBody] attribute in your controller's parameter list like this:

public void ReceiveData([FromBody] List<DataModel> dataModels)

It may help if you remove the following lines:

traditional: true

and

charset=utf-8

Also, consider taking out those details from the ajax call. This should result in a populated list being passed to the controller.

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

Utilizing Ajax: Sending Customized Data to a Modal

Having never worked with jquery before, I struggled to find a solution for my specific case. On the cockpit.php page, I have a form that retrieves content from a mysql database. Currently, I am able to display this content in a div on the same cockpit.php ...

Where should Babel and Webpack be placed in your package.json file - under devDependencies or Dependencies?

I'm a beginner when it comes to npm and I have doubts on what should be included in dependencies as opposed to devDependencies. I understand that testing libraries belong in dev, but what about tools like babel and webpack? Should they also be categor ...

Exploring CryptoJS in a Vue.js project

https://github.com/brix/crypto-js I successfully installed CryptoJS using npm i crypto-js. However, I am facing difficulty in integrating it into my project. When I attempt to use the following code: // Decrypt var bytes = CryptoJS.AES.decrypt(cipher ...

Developing Webpart Postback logic in C# script

I am currently facing challenges with SharePoint webparts programming. I am unsure about how to trigger a postback for an object at a specific time. I have come across suggestions to use "javascript" for this purpose, but I am having trouble understanding ...

I implemented a proxy in my project to handle cross-domain requests, however, the requested address changes when I make a

Unable to Cross Domains http://localhost:8080/api/login has to be redirected to http://localhost:8080/index.html proxyTable: { '/api': { target: 'http://47.106.74.67:8080', changeOrigin: true, pathRewrite: ...

How to retrieve the response body in C# using Unirest

Learn more about using Unirest for .Net at https://github.com/mashape/unirest-net/ Take a look at the code snippet below: Task<HttpResponse<MyClass>> response = Unirest.get("") .header("X-Mashape-Authorization", "") .asJsonAsync<My ...

Transferring information to a partial view using a jQuery click event

In my Index view, there is a list of links each with an ID. My goal is to have a jQueryUI dialog box open and display the ID when one of these links is clicked. Currently, I am attempting to use a partial view for the content of the dialog box in order to ...

How to achieve multiplication in Javascript without utilizing the * operand

Challenge 1 Criteria: This problem involves working with two positive integers N and M. Outcome: Upon completion, the function should output the result of multiplying N and M. For instance, if you input 5 and 8 into the function, it should calculate and ...

An incorrect format is being utilized for updating "ChromeOptions.AddUserProfilePreference" in Selenium using C#

Updating Chrome Profile preferences in Selenium C# to make a popup disappear can be achieved by including the following line as part of Chrome Options. string url = "https://google.com"; string envName = "xyz.qa"; ChromeOptions.AddUser ...

What are the steps to storing numerical inputs as variables using jQuery and then using them to perform calculations in order to update the input numbers

Currently, I am in the process of creating a BMI calculator using HTML and jQuery. <form id="bmiCalculator"> <fieldset> <legend>BMI Calculator:</legend> <p> <label>Height: ...

Facing an error response with the Javascript callout policy in Apigee. Any suggestions on fixing this issue?

This is the code snippet I'm using in my JavaScript callout policy var payload = JSON.parse(request.content); var headers = {'Content-Type' : 'application/json'}; var url = 'https://jsonplaceholder.typicode.com/posts'; va ...

Selection determines the value of two fields

This form has predefined values that are used to create a link, but the issue is that these values vary depending on the location. Can you assist me with this problem? <input type="radio" id="iconapp1" name="department" value="1250"/><label for ...

Oops! You can only have one parent element in JSX expressions

I'm working on creating a password input box, but I keep encountering an error when integrating it into my JS code. Here's the snippet of my code that includes TailwindCSS: function HomePage() { return ( <div> <p className=&q ...

An issue with the AngularJS [$parse:syntax] error has been identified when using specific data in the

I encountered an issue when attempting to create an AngularJS ui-grid table with data that includes a '(' and then whitespace before the closing ')' within a string. This resulted in an AngularJS error message: Syntax Error: Token &a ...

What is the most efficient way to use map-reduce in TypeScript to filter a list based on the maximum value of an attribute?

Recently, I came across a list that looked something like this: let scores = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}, {name: "D", skills: 60, ...

Utilize Google Drive and scripts to incorporate map images into a React application

I'm currently working on setting up an album feature on my react website for a friend, and I would like the images in the album to be linked to a Google Drive so that he can easily upload new images whenever he wants. After successfully inserting the ...

The Next.js error message reads: 'Issue with setting properties on undefined entity (specifically 'hook')'

This issue seems to occur either when the app is launched or when updating the Redux state. It may not show up consistently for every state update, but for some reason it persists throughout the entire app. What I have attempted so far: Removing node mod ...

Sequelize associations are not functioning optimally as expected

Trying to display a nested relationship: Cat.hasMany(legs) Leg.belongsTo(cat) Leg.hasOne(paw) paw.hasMany(leg) This is the Cat Model: module.exports = (sequelize, DataTypes) => { const Cat = sequelize.define('Cat', { us ...

Tips for enabling multiple v-list-group components to remain open simultaneously (bypassing the default Vue behavior)

Currently, I am facing an issue with Vue's default behavior where only one v-list-group can be open at a time. I am using Vuetify 2.6 and have attempted to use the multiple prop without success. Additionally, individually assigning the :value prop to ...

Updating a section of a webpage using jQuery Mobile

I'm currently facing an issue with modifying a specific section of my webpage. Although this problem has been discussed before, I haven't found a satisfactory solution yet. The element in red on the page needs to change dynamically based on the ...