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

Surprising pause in the menu transition animation

Currently, I am in the process of developing a menu that seems to have some flaws. One issue is that it appears a bit choppy, but the more concerning problem is the half-second delay after clicking an item before it animates. The concept behind this menu ...

Encountering yet another frustrating issue with z-index not functioning properly in versions of IE above 7, despite extensive research yielding no solution

I have scoured numerous resources and read countless articles on how to resolve z-index issues in IE 7, 8, and 9. However, none of the suggested solutions seem to work for my particular situation. The issue at hand is that I have interactive content posit ...

React: A guide to properly utilizing PropTypes inheritance

I've created a wrapper component for React Router Dom and Material UI: import Button from '@material-ui/core/Button'; import React from 'react'; import { Link as RouterLink } from 'react-router-dom'; const forwardedLink ...

The Mantine date picker is causing an error stating that objects are not valid as a React child

I'm currently experimenting with utilizing Mantine Date in NextJS. The goal is to have the selected date displayed in the HTML text heading when a user clicks on it. For instance, if a user selects January 1st, 2023, the text should show like this: Da ...

Increasing variable in angular template (nested ng-repeat)

I am facing a similar situation as described in the example below, and I need to generate a serial number for each row independently for each mark record. Here is the Java script Object structure: $scope.childsList = [ { id:12346, ...

A guide on mapping an array and removing the associated element

I have an array called responseData, which is used to display the available card options on the screen. public responseData = [ { id: 1399, pessoa_id: 75898, created_at: '2022-11-08T16:59:59.000000Z', holder: 'LEONARDO ', validade: ...

Cufon failing to load following an ajax call

At first, cufon is used to replace the text on the main page. However, when another page file is loaded, cufon does not apply its replacement to the newly loaded content. Why is that? I tried adding cufon.refresh(); as the last function in the chain. I c ...

Tips for retrieving the value of a table cell when the checkbox in the corresponding row is selected

Within my project, I am utilizing a table. The html code I am using is as follows: <table id="assTB" border="1px" cellspacing="0"> <colgroup> <col style="width:15%"> <col style="width:15%"> <col sty ...

Enhancing a specific element in a view using Node.js alongside Express and EJS

My goal is to modify value2 on the server side and update the view accordingly. The question at hand is: How can I efficiently refresh the view with only the new value2? Server: var express = require("express"); var app = express(); app.set('view ...

Modify the width of the progress bar in Bootstrap using AngularJS

I'm new to AngularJS and I'm attempting to dynamically update the width of a progress bar based on changes in my controller. Here is what I currently have: <span id="percentage">$ {{getTotal()}} ({{getPercentage()}}%)</span> <div ...

Extract information from continuously updated Excel file that remains open at all times, automatically refreshing every 10 seconds

Is it feasible to retrieve data from an Excel file that remains open and continuously updates its values? This can be accomplished using various methods such as SQL, Python, Excel macros, or a text document. The Excel file in question is connected to live ...

There seems to be a potential object cycle that was identified by System.Text.Json.JsonException

Currently, I am working on a practice project that involves developing a .Net blog style API. Throughout my work, I have encountered an error related to the structure of my classes - User, Post, and Comment. Each Comment class has references to both Post a ...

React form not detecting the Enter key press in onSubmit event

Currently, I am in the process of working on a form that includes a tag input feature. The issue I am facing is that when a user enters a tag and presses enter, it not only adds the tag to a specific array but also submits the form. While I can use the e.p ...

Deliver personalized feedback in an asp.NET REST API endpoint for unsuccessful requests

I have a RESTful API that includes an endpoint structured like this: [Route("create")] [HttpPost] public object CreateStuff ([FromBody] MyParams args) { //... } For simplicity's sake, imagine MyParams as an object containing only one fi ...

Myfaces Apache prioritizes rendering datatable before handling ajax events

I have a selectOneMenu that is responsible for controlling the content displayed in a datatable. Below is the relevant code snippet: <ui:composition template="/WEB-INF/templates/BasicTemplate.xhtml"> <ui:define name="content"> <br /&g ...

What steps do I need to take in order to activate CORS for a .NET Core 3.1 Google Cloud

I have created a PDF protection service function on Google Cloud using .NET Core 3.1, but I am facing issues when trying to call the service from my React.js website due to CORS blocking it. namespace SimpleHttpFunction { public class Function : I ...

Trigger the OnAppend event for a jQuery element upon its insertion into the DOM

After writing a code snippet that generates custom controls, I encountered an issue where the custom scrollbar was not being applied because the element had not yet been appended to the DOM. The code returns a jQuery element which is then appended by the c ...

What is the best way to open a browser window at a quarter of its default size?

Is there a way to open a window at 25% of its default device browser window size? I attempted the code below, which worked. However, it only accepts pixel inputs and not relative % values. This makes it non-scalable across various devices. window.resizeT ...

Transform the array into an associative array

Below is the array I am working with: print_r($data); When printed in PHP, the result looks like this: $data=Array( [0] => stdClass Object ( [name] => location [value] =>lko ) [1] => stdClass Object ( [n ...

Steps for adding multiple images to a page in a React application:1. Create a

Having trouble displaying images on a React page. I have a directory with 30 images that I want to display on the page (.jsx file). Instead of exporting each image individually, is there a faster way to accomplish this task? Any ideas or suggestions would ...