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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:13:32  来源:igfitidea点击:

jQuery Ajax POSTing array to ASP.NET MVC Controller

asp.net-mvcjqueryhttp-post

提问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 orderedIdsis a JavaScript number array (e.g. var orderedIds = [1, 2]).

orderedIdsJavaScript 数字数组在哪里(例如var orderedIds = [1, 2])。

The handling Controllermethod is:

处理Controller方法为:

[HttpPost]
public void UpdateNoteOrder(long[] orderedIds, long unixTimeMs)
{
    ...
}

When I put a Debugger.Break()in UpdateNoteOrder(), orderedIdsis nullin the Watch window. (unixTimeMs, however, has a numeric value.)

当我把一个Debugger.Break()UpdateNoteOrder()orderedIdsnull在监视窗口。(unixTimeMs但是,有一个数值。)

How do I pass the number array through $.ajax()such that orderedIdsis a long[]in my controller?

我如何通过数字阵列通过$.ajax()这样orderedIdslong[]在我的控制?

回答by Darin Dimitrov

Just set the traditionalparameter 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()
    }
});