What is the best method to send a JSON object from an Ajax call to an ASP.net page?

Anyone know why this code is failing to send JSON objects to a MVC controller via POST? Any suggestions?

JS

    function Update()
    {
        var objects = $(".Classes");
        items = [];
        objects.each(function () {
            items .push({
                "Id": $(this).find(".input").attr('id'),
                "Value": $(this).find(".input2").val()
            });
        });
        $.ajax({
            type: "POST",
            url: "/A/Update",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },

            data: JSON.stringify(items),

            contentType: "application/json",
            dataType: "json",
            success: function (response) {
            }
        });
    }

Model

public class Update{
            public string Id{get;set;}
            public string Value{ get; set; }
        }

Task

[HttpPost("Update")]
        public async Task<JsonResult> Update(IList <Update> items)
        {...}

Although the task runs without error, the JSON objects fail to deserialize into the model, resulting in an empty list of items.

Answer №1

To ensure successful sending of Post data, it is necessary to modify your code

data:{"items":JSON.stringify(items)}
. You need to specify the name of the post data before making any changes to the code.

function Update()
    {
        var objects = $(".Classes");
        items = [];
        objects.each(function () {
            items .push({
                "Id": $(this).find(".input").attr('id'),
                "Value": $(this).find(".input2").val()
            });
        });
        $.ajax({
            type: "POST",
            url: "/A/Update",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },

            data:{"items":JSON.stringify(items)},

            contentType: "application/json",
            dataType: "json",
            success: function (response) {
            }
        });
    }

Answer №2

To ensure that the model binding system can read post data from the request body and bind it to your object, simply make one small adjustment by using [FromBody]:

public async Task<JsonResult> Update([FromBody]IList<Update> items)

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

Modify the placeholder HTML once a username has been submitted

In order to maximize efficiency, I have included an input box with a placeholder that reads: <input id="username-search" placeholder="explore another user's work"> Once the username is entered, I want to modify the placeholder text to somethin ...

Tips for fixing a type error in javascript/cypress

While learning cypress and javascript, I encountered this type error: TypeError: _testElements.default.selectionRow is not a function I have thoroughly reviewed the documentation for cypress but cannot seem to find any errors in my code. I'm hoping ...

Retrieve JSON response from a POST request

When I send the data using POST method, I receive the answer in JSON format. However, if I switch to plain text instead of JSON, it works fine but not with JSON. No error message is displayed in the application. If status = true -> Registration succes ...

Vue.js, when using async await functions, sometimes renders blank results

Currently working on a JavaScript project that requires the use of await/async to fetch data from an API. Here is a snippet of my code: const fetchData = async () => { let data = []; for (let i = 0; i < this.data.length; ...

Fetching works flawlessly in the local environment, but encounters issues when deployed

Fetching Data Problem in Vercel Deployment vs Localhost I'm encountering a problem with fetching data in my React app. Here's a simplified version of the code snippet: useEffect(() => { async function fetchData() { const res = await fet ...

Update the second dropdown list based on the selection made in the first dropdown list in Vue.js

My goal is to dynamically change the options in the second select list based on the value selected in the first one. I initially achieved this by creating two separate Vue instances for each select, but I wanted a more streamlined approach for a cleaner ap ...

Websites using UTF-8 encoding facing challenges with specific browsers

I recently created a web application using JSP for the presentation layer. In each JSP file, I included charset definitions like this: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> ... How ...

What is the best way to modify a node_module file consisting of only a few exported variables, which is heavily utilized in the entire module? (with demonstration)

I have integrated a node module with the file structure displayed below. Inside the file node_core_ctx.js, I found this code snippet: const EventEmitter = require('events'); let sessions = new Map(); let publishers = new Map(); let idlePlayers ...

Provide a random number that is not already listed in the array

I am working on creating a function that accepts an array as input, generates a random number between 1 and 10, keeps generating numbers until it finds one that is not in the array, and then returns that number. For more information and to see the code in ...

What is the process of transmitting an array of data from Angular to a controller?

Recently, I started using AngularJS alongside asp.net MVC 5. Within my Angular code, I have an array called $scope.selectedRooms = []; where I push items into it. I want to send the data from this array to the controller after checking certain conditions. ...

Exploring JSON data on an iPhone手机 is a fascinating

Similar Question: How to handle JSON parsing in iOS applications Here is the JSON data that I am working with: NSString *jsonResult = @"{\"code\":\"000\",\"message\":\"success\",\"datas\":[{\"dat ...

Changing the background color of a PHP input based on the webpage being viewed - here's how!

I'm in the process of creating a website where each page will have its own unique background color. Additionally, I am using a PHP input for both the header and footer sections, which need to change their background colors based on the specific webpa ...

Can you group polygons in layers using Phaser?

My goal is to animate two polygons: one that remains stationary and another that changes shape while moving. The challenge is to ensure that the stationary polygon always stays on top when overlapping. This is my proposed solution: (function() { "use ...

Concealing axis lines within the initial circular grid or opting not to include them

Is there a way to incorporate some whitespace within the center circle of the radar chart? I'm aiming for the axis to commence at 1 radius (the initial circular line) or perhaps have the stoke set to 0 for the primary radius. Any assistance would be g ...

Managing the absence of data in JSONParser in Java

Here is an example of my JSONParser method: public ArrayList<Meaning> parseMeaning (JSONObject object) { ArrayList<Meaning> arrayList = new ArrayList<Meaning>(); try { JSONObject value = object.g ...

Here's a unique version: "Strategies for effectively closing a modal when moving to a

I'm currently working with react-router-dom and material UI modal, and I am looking for a way to automatically hide the modal whenever the user navigates to another page. Here is my App component: const App = () => ( <BrowserRouter> &l ...

Searching for ways to filter out specific tags using regular expressions

Can anyone provide a quick solution to help me with this issue? I am trying to remove all html tags from a string, except for the ones specified in a whitelist (variable). This is my current code: whitelist = 'p|br|ul|li|strike|em|strong|a', ...

Having problems with Javascript and CSS not playing well together?

I have implemented a button from this source, but it does not appear correctly on my page. You can view the screenshot here. It seems like there is a conflict between the saved changes and the CSS. How can I resolve this issue? In addition, I am facing ...

Implement a jQuery loop that utilizes the fadeIn effect

Currently, I have a basic jQuery function in place to generate a small image slider: function gridhover() { $(".grid-item .slide-image").each(function(index) { $(this).delay(400*index).fadeIn(300); }); } $( ".grid-item" ).hover(function() ...

What is the most effective method for displaying an error code when a JavaScript error occurs?

I'm currently dealing with a library that is throwing errors: throw new Error('The connection timed out waiting for a response') This library has the potential to throw errors for various reasons, making it challenging for users to handle ...