Home >Backend Development >C++ >How to Successfully Pass an Array of Objects to an MVC Controller Using jQuery Ajax?

How to Successfully Pass an Array of Objects to an MVC Controller Using jQuery Ajax?

DDD
DDDOriginal
2025-01-21 17:26:09447browse

How to Successfully Pass an Array of Objects to an MVC Controller Using jQuery Ajax?

Passing array of objects to MVC controller method using jQuery Ajax

When trying to pass an array of objects to a method of an MVC controller using jQuery's ajax() function, you may encounter a situation where the "things" parameter in the controller method is empty. This problem may occur even when using List as parameter type.

The solution to this problem is as follows:

<code class="language-javascript">things = JSON.stringify({ 'things': things });</code>

By wrapping the "things" array in a JSON object this way you can successfully pass the array to the controller method.

The complete code for this implementation is as follows:

<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: '/Home/PassThings',
        data: things,
        success: function () {          
            $('#result').html('"PassThings()" successfully called.');
        },
        error: function (response) {          
            $('#result').html(response.responseText); // 使用 response.responseText 获取错误信息
        }
    }); 
});</code>
<code class="language-csharp">public void PassThings(List<Thing> things)
{
    // 处理things数据
}

public class Thing
{
    public int Id { get; set; }
    public string Color { get; set; }
}</code>

Please note two important aspects of this implementation:

  1. It is important to use the following settings in the ajax() function:
<code class="language-javascript">        contentType: 'application/json; charset=utf-8',
        dataType: 'json',</code>
  1. To pass an array of objects to an MVC controller method, use the following JSON format:
<code class="language-javascript">
JSON.stringify({ 'things': things })
```  并且在`failure`回调函数中,使用 `response.responseText` 获取服务器返回的错误信息,以更准确地处理错误。


通过以上步骤,您可以确保将对象数组正确地传递给您的MVC控制器。</code>

The above is the detailed content of How to Successfully 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!

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