JQuery AJAX POSTing array for ASP.NET MVC Controller

Something is missing for me. I have jQuery JavaScript:

$.ajax({ type: "POST", url: "/update-note-order", dataType: "json", data: { orderedIds: orderedIds, unixTimeMs: new Date().getTime() } }); 

Where orderedIds is an array of JavaScript numbers (for example, var orderedIds = [1, 2] ).

Controller processing method:

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

When I put a Debugger.Break() in UpdateNoteOrder() , orderedIds is null in the viewport. ( unixTimeMs , however, has a numerical value.)

How to pass an array of numbers through $.ajax() so that orderedIds long[] in my controller?

+57
jquery asp.net-mvc
Dec 09 '10 at 19:03
source share
2 answers

Just set traditional 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, since the mechanism for serializing objects in query parameters has changed.

+123
Dec 09 '10 at 19:09
source share

you will need to swap orderedId into a param array or the controller will not 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() } }); 
0
Dec 09 '10 at 19:08
source share



All Articles