我正在尝试使用以下方法将对象数组传递到 MVC 控制器方法中
jQuery 的 ajax() 函数。当我进入 PassThing() C# 控制器方法时,
参数“things”为空。我已经尝试过使用列表类型
的论点,但这也不起作用。我究竟做错了什么?
<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 });
这是完整的代码。
$(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; }
}
我从中学到了两件事:
-
contentType 和 dataType 设置在 ajax() 函数中是绝对必要的。如果他们失踪了,那就不行了。经过多次尝试和错误,我发现了这一点。
-
要将对象数组传递给 MVC 控制器方法,只需使用 JSON.stringify({ 'things': things }) 格式。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)