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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Great one. Instead of using Viewmodel for a simple string array, traditional true does it. upvoted !
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.
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()
    }
});

6 Comments

This does not work. In UpdateNoteOrder, orderedIds is still null.
if it doesn't work, check your code first, this is taken directly from the jquery documentation api.jquery.com/jQuery.param You may want to be sure you are correct before rejecting an answer
I can confirm also that this doesn't work (I wrote a sample application in order to test it).
I tested with 1.3.2, I see now the changes were in 1.4. I guess I didn't update jquery recently.
in jquery 1.3.2 you don't even need $.param, it will work out of the box. Unfortunately in jquery 1.4 this behavior has changed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.