Binding JS array to C# list in ASP.NET MVC

Hey guys,

This will be a very short post about a problem that I faced this week while writing some JavaScript code.

At first sight, the acticity should be a very simple one: send an array of data from client to server via AJAX. My pair and I tried a simple POST request similiar to the code below:

image1

Unfortunately, the parameter is always null in the server.

image2

After some time wasted reading the code looking for erros, we decided to verify the post data sent by the browser. That is what Firebug showed to us:

image3

We then realized that the serialization of the array is wrong. But why? Let’s take a look at jQuery’s documentation, more specifically about jquery.Ajax() data setting.

data: Data to be sent to the server. It is converted to a query string, if not already a string. It’s appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.

Traditional option regards the parameter serialization style. That is a clue. Going a little deeper in our search we found this:

“As of jQuery 1.4, the $.param() method serializes deep objects recursively to accommodate modern scripting languages and frameworks such as PHP and Ruby on Rails. You can disable this functionality globally by setting jQuery.ajaxSettings.traditional = true;.”

Now, we know the reason. Due to the way other web frameworks handle JSON parameters, jQuery serialization changed the way arrays are serialized. Therefore, we as .NET developers need to use the traditional = true setting.

image4

And Boommmm… it works perfectly. Let’s take a look at the request’s paremeters.

image5

That is what ASP.NET MVC needs Alegre

That’s it guys.

See you,
Fernando

One thought on “Binding JS array to C# list in ASP.NET MVC

  1. Found a better way:

    If you are going to send JSON to the server you need to JSON.stringify the data and specify the contentType as application/json :

    $.ajax({
    type: “POST”,
    url: “@Url.Action(“UpdateCart”, “Cart”)”,
    data: JSON.stringify(items),
    success: function () {
    alert(“Successfully updated your cart!”);
    },
    contentType: ‘application/json’
    });

Leave a comment