58

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?

tereško
  • 58,060
  • 25
  • 98
  • 150

2 Answers2

125

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Unfortunately in my Rails application, I get only last element of the array. I verified that browser is sending array correctly. In above example, I replaced `orderedIds: orderedIds` with `'orderedIds[]': orderedIds` to make it work for Rails. – Amit Patel Aug 28 '12 at 11:27
  • 1
    Great one. Instead of using Viewmodel for a simple string array, traditional true does it. upvoted ! – Sakthivel Sep 25 '13 at 06:39
  • I've spent an unbelievable amount of time trying to figure out this issue in my code and I stumbled across this gem. Thanks for your help. – Jeremy Feb 14 '15 at 16:08
0

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()
    }
});
Jeremy B.
  • 9,168
  • 3
  • 45
  • 57