Showing posts with label jQuery 1.4.x Ajax traditional option. Show all posts
Showing posts with label jQuery 1.4.x Ajax traditional option. Show all posts

Wednesday, May 30, 2012

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.

jQuery code

$.ajax({
   type: 'POST',
   url: "/MyController/MyAction",
   data: { 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". 

We 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:

$.ajax({
   type: 'POST',
   url: "/MyController/MyAction",
   data: { myArray: ids },
   traditional: true
});

You can read more about the new param serialization here.