jQuery Ajax POSTing array to ASP.NET MVC Controller

asp.net MvcJqueryHttp Post

asp.net Mvc Problem Overview


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?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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.

Solution 2 - asp.net Mvc

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()
    }
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAgileMeansDoAsLittleAsPossibleView Question on Stackoverflow
Solution 1 - asp.net MvcDarin DimitrovView Answer on Stackoverflow
Solution 2 - asp.net MvcJeremy B.View Answer on Stackoverflow