Using jQuery AJAX to Send an Array of Objects to an MVC Controller
When sending an array of objects to an MVC controller using jQuery's ajax()
method, a common problem is receiving a null
value for the array in the controller. This can happen even when the controller parameter is correctly defined as List<T>
.
The solution involves two key adjustments:
Specify JSON Data Type: The ajax()
call must explicitly set both contentType
and dataType
to 'application/json; charset=utf-8'
.
Serialize Data with JSON.stringify(): The JavaScript array of objects needs to be converted into a JSON string using JSON.stringify()
. Crucially, this string should encapsulate the array within a property (e.g., 'things').
Here's the corrected code implementing these changes:
<code class="language-javascript">$(document).ready(function () { const things = [ { id: 1, color: 'yellow' }, { id: 2, color: 'blue' }, { id: 3, color: 'red' } ]; const data = JSON.stringify({ things: things }); $.ajax({ contentType: 'application/json; charset=utf-8', dataType: 'json', type: 'POST', url: '/Home/PassThings', data: data, success: function () { $('#result').html('"PassThings()" successfully called.'); }, error: function (response) { $('#result').html(response.responseText); // Display error details } }); });</code>
And the corresponding C# controller method:
<code class="language-csharp">public void PassThings(List<Thing> things) { // Access the 'things' array here } public class Thing { public int Id { get; set; } public string Color { get; set; } }</code>
By following these steps, you'll successfully transmit the array of objects to your MVC controller method via jQuery AJAX. Note the change from failure
to error
in the AJAX call for better error handling, displaying the response text for debugging purposes.
The above is the detailed content of How to 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!