Home >Backend Development >C++ >How to Correctly Pass an Array of Objects to an MVC Controller using jQuery Ajax?
Use jQuery Ajax to process object arrays in MVC (PassThing() method)
In an MVC application, passing an array of objects to a controller method using jQuery's ajax() function can be challenging. The PassThing() method expects an array of Thing objects, but the array is passed in as null.
The problem
The provided code initializes an array of Thing objects and attempts to pass it to the PassThing() method using JSON.stringify(). The error occurs because the format of the data sent to the server does not match the format expected by the PassThing() method.
Solution
To solve this problem, use JSON.stringify({ 'things': things }) to convert the array into an object with the "things" property. This object structure matches the parameters expected by the PassThing() method. The following is the modified jQuery code:
<code class="language-javascript">$(document).ready(function () { var things = [ { id: 1, color: 'yellow' }, { id: 2, color: 'blue' }, { id: 3, color: 'red' } ]; things = JSON.stringify({ 'things': things }); $.ajax({ contentType: 'application/json; charset=utf-8', dataType: 'json', type: 'POST', url: '/Xhr/ThingController/PassThing', data: things }); });</code>
Other notes
To ensure successful data delivery:
The above is the detailed content of How to Correctly Pass an Array of Objects to an MVC Controller using jQuery Ajax?. For more information, please follow other related articles on the PHP Chinese website!