jQuery Ajax POSTing array to ASP.NET MVC Controlle

2020-01-26 04:36发布

I'm missing something here. I've got this 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]).

The handling Controller method is:

[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.)

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

2条回答
smile是对你的礼貌
2楼-- · 2020-01-26 05:11

you'll need to turn orderedId's into a param array, or the controller won't see it

$.param({ orderedIds: orderedIds });  

in your code:

$.ajax({
    type: "POST",
    url: "/update-note-order",
    dataType: "json",
    data: {
        orderedIds: $.param({ orderedIds: orderedIds }),
        unixTimeMs: new Date().getTime()
    }
});
查看更多
甜甜的少女心
3楼-- · 2020-01-26 05:17

Just set the traditional parameter to 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.

查看更多
登录 后发表回答