Wednesday, June 9, 2010

jQuery 1.4.x Ajax traditional option

I have a very simple jQuery code that basically sends an array of integer back to my ASP.NET MVC Controller class.

$.post ("/MyController/MyAction", { myArray: ids });
My controller action:
public void MyAction (int[] myArray) {
   // do stuff here ...
But upon upgrading to jQuery 1.4.x, it does not work anymore. The param "myArray" in MyAction is always null.

During debugging, I found out that somehow it sent the post data as "myArray[]" instead of "myArray". Of course, you cannot name a parameter name with brackets in C# so simply renaming the parameter name in MyAction won't work.

After some readings, it turns out that this is a change in the jQuery 1.4 release - it changes the way it does param serialization. But, jQuery also provides a new flag in $.ajax to override the default behavior (and go back to use the old way of param serialization): the "traditional" option in $.ajax. So here is my revised code:
   type: 'POST',
   url: "/MyController/MyAction",
   data: { myArray: ids },
   traditional: true
You can read more about the new param serialization here and here (under "Nested param serialization" section).

No comments: