jQuery Ajax POSTing 数组到 ASP.NET MVC 控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4402036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Ajax POSTing array to ASP.NET MVC Controller
提问by AgileMeansDoAsLittleAsPossible
I'm missing something here. I've got this jQuery JavaScript:
我在这里遗漏了一些东西。我有这个 jQuery JavaScript:
$.ajax({
type: "POST",
url: "/update-note-order",
dataType: "json",
data: {
orderedIds: orderedIds,
unixTimeMs: new Date().getTime()
}
});
Where orderedIds
is a JavaScript number array (e.g. var orderedIds = [1, 2]
).
orderedIds
JavaScript 数字数组在哪里(例如var orderedIds = [1, 2]
)。
The handling Controller
method is:
处理Controller
方法为:
[HttpPost]
public void UpdateNoteOrder(long[] orderedIds, long unixTimeMs)
{
...
}
When I put a Debugger.Break()
in UpdateNoteOrder()
, orderedIds
is null
in the Watch window. (unixTimeMs
, however, has a numeric value.)
当我把一个Debugger.Break()
在UpdateNoteOrder()
,orderedIds
是null
在监视窗口。(unixTimeMs
但是,有一个数值。)
How do I pass the number array through $.ajax()
such that orderedIds
is a long[]
in my controller?
我如何通过数字阵列通过$.ajax()
这样orderedIds
是long[]
在我的控制?
回答by Darin Dimitrov
Just set the traditional
parameter to true
:
只需将traditional
参数设置为true
:
$.ajax({
type: "POST",
url: "/update-note-order",
dataType: "json",
traditional: true,
data: {
orderedIds: orderedIds,
unixTimeMs: new Date().getTime()
}
});
Since jquery 1.4 this parameter exists because the mechanism to serialize objects into query parameters has changed.
从 jquery 1.4 开始,这个参数存在是因为将对象序列化为查询参数的机制发生了变化。
回答by Jeremy B.
you'll need to turn orderedId's into a param array, or the controller won't see it
您需要将orderedId 转换为参数数组,否则控制器将看不到它
$.param({ orderedIds: orderedIds });
in your code:
在您的代码中:
$.ajax({
type: "POST",
url: "/update-note-order",
dataType: "json",
data: {
orderedIds: $.param({ orderedIds: orderedIds }),
unixTimeMs: new Date().getTime()
}
});