使用jQueryAjax将对象列表传递给MVC控制器方法我试图使用jQuery的Ajax()函数将一个对象数组传递给MVC控制器方法。当我进入PassThing()C#控制器方法时,参数“Things”为NULL。我尝试过使用一种类型的List作为参数,但这也不起作用。我做错什么了?<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; }
}}
2 回答
浮云间
TA贡献1829条经验 获得超4个赞
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; }}在Ajax()函数中,contentType和dataType设置是绝对必要的。如果他们失踪了就没用了。经过多次反复试验,我发现了这一点。 要将对象数组传递给MVC控制器方法,只需使用JSON.strgify({‘Things’:Things})格式即可。
ABOUTYOU
TA贡献1812条经验 获得超5个赞
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }];$.post('@Url.Action("PassThings")', { things: things },
function () {
$('#result').html('"PassThings()" successfully called.');
});[HttpPost]public void PassThings(IEnumerable<Thing> things){
// do stuff with things here...}- 2 回答
- 0 关注
- 348 浏览
添加回答
举报
0/150
提交
取消
