Home >Backend Development >C++ >How to Properly Pass a JavaScript Array to an MVC Controller Using jQuery AJAX?

How to Properly Pass a JavaScript Array to an MVC Controller Using jQuery AJAX?

DDD
DDDOriginal
2025-01-21 17:11:13715browse

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:

  • contentType and dataType must be set: These settings are crucial for the ajax() function.
  • Correct JSON stringification: To pass an array of objects, use the JSON.stringify({ 'things': things }) format.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn