问题描述
我正在尝试将对象数组传递给 MVC 控制器方法,使用jQuery 的 ajax() 函数.当我进入 PassThing() C# 控制器方法时,参数事物"为空.我已经尝试使用一种 List for论点,但这也不起作用.我做错了什么?
I'm trying to pass an array of objects into an MVC controller method using jQuery's ajax() function. When I get into the PassThing() C# controller method, the argument "things" is null. I've tried this using a type of List for the argument, but that doesn't work either. What am I doing wrong?
<script type="text/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)
});
});
</script>
public class ThingController : Controller
{
public void PassThing(Thing[] things)
{
// do stuff with things here...
}
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}
}
推荐答案
使用 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!
这篇关于使用 jQuery Ajax 将对象列表传递给 MVC 控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!