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
Release: 2025-01-21 17:26:09
Original
445 people have browsed it

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:

things = JSON.stringify({ 'things': things });
Copy after login

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:

$(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 获取错误信息
        }
    }); 
});
Copy after login
public void PassThings(List<Thing> things)
{
    // 处理things数据
}

public class Thing
{
    public int Id { get; set; }
    public string Color { get; set; }
}
Copy after login

Please note two important aspects of this implementation:

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


通过以上步骤,您可以确保将对象数组正确地传递给您的MVC控制器。
Copy after login

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 of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template