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:
  1. public void MyAction (int[] myArray) {
  2. // do stuff here ...
  3. }
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:
  1. $.ajax({
  2. type: 'POST',
  3. url: "/MyController/MyAction",
  4. data: { myArray: ids },
  5. traditional: true
  6. });
You can read more about the new param serialization here and here (under "Nested param serialization" section).

No comments: