Home >Backend Development >C++ >How to Properly Pass a JavaScript Array to an MVC Controller Using jQuery AJAX?
Passing array to MVC controller method via jQuery Ajax
When trying to send an array of objects to a controller method via jQuery's ajax() function, the received parameter may appear to be null. To solve this problem, we implemented a solution using JSON.stringify().
Consider the following scenario:
<code class="language-javascript">$(document).ready(function () { var things = [ { id: 1, color: 'yellow' }, { id: 2, color: 'blue' }, { id: 3, color: 'red' } ]; $.ajax({ contentType: 'application/json; charset=utf-8', dataType: 'json', type: 'POST', url: '/Xhr/ThingController/PassThing', data: JSON.stringify({ 'things': things }) }); });</code>
In controller:
<code class="language-csharp">public class ThingController : Controller { public void PassThing(List<Thing> things) { // 在此处处理`things` } public class Thing { public int Id { get; set; } public string Color { get; set; } } }</code>
Key takeaways from this method:
This method allows seamless transfer of an array of objects to an MVC controller method via jQuery's ajax() function.
The above is the detailed content of How to Properly Pass a JavaScript Array to an MVC Controller Using jQuery AJAX?. For more information, please follow other related articles on the PHP Chinese website!