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 });
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 获取错误信息 } }); });
public void PassThings(List<Thing> things) { // 处理things数据 } public class Thing { public int Id { get; set; } public string Color { get; set; } }
Please note two important aspects of this implementation:
contentType: 'application/json; charset=utf-8', dataType: 'json',
JSON.stringify({ 'things': things }) ``` 并且在`failure`回调函数中,使用 `response.responseText` 获取服务器返回的错误信息,以更准确地处理错误。 通过以上步骤,您可以确保将对象数组正确地传递给您的MVC控制器。
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!