更新时间:2023-02-25 19:14:47
根据 NickW 的建议,我能够使用 things = JSON.stringify({ 'things': things });
这是完整的代码.
Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things });
Here is the complete code.
$(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.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
public void PassThings(List<Thing> things)
{
var t = things;
}
public class Thing
{
public int Id { get; set; }
public string Color { get; set; }
}
我从中学到了两件事:
ajax() 函数中的 contentType 和 dataType 设置是绝对必要的.如果它们丢失,它将无法工作.经过多次反复试验,我发现了这一点.
The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error.
要将对象数组传递给 MVC 控制器方法,只需使用 JSON.stringify({ 'things': things }) 格式.
To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.
我希望这对其他人有帮助!
I hope this helps someone else!