Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you serialize a JS array so Asp.net MVC can bind it to a c# list?

I am trying to send a jquery sortable list of items to my MVC method for data processing. Currently I am trying to send it via the following code:

var data = {};
data.projectId = projectId;
data.publishedSectionIds = $('#section_list').sortable('toArray');

// Perform the ajax
$.ajax({ url: '/Project/Publish',
    type: 'POST',
    data: data,
    success: function (result) {
        alert(result.message);
    } 
});

The problem with this code is it makes the Post parameters look like this:

projectId=2&publishedSectionIds[]=1&publishedSectionIds[]=2

The issue with this (as can be seen by the solution to this question) is that MVC only seems to serialize into a List if the post parameters do NOT have brackets.

How can I serialize the javascript array so my action with a List<int> parameter model binds correctly?


Edit: The action's signature looks like:
 public ActionResult Publish(int projectId, List<int> publishedSectionIds)
like image 832
KallDrexx Avatar asked Jul 28 '10 00:07

KallDrexx


1 Answers

try adding the following option traditional: true

eg

$.ajax({ url: '/Project/Publish',
    type: 'POST',
    data: data,
    traditional: true,
    success: function (result) {
        alert(result.message);
    } 
});

see

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;.

http://api.jquery.com/jQuery.param/

like image 175
Okeydoke Avatar answered Sep 25 '22 17:09

Okeydoke