Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit array param with jQuery ajax/load

public ActionResult DoSomething(string[] arr, bool someBool, int someInt) { }

trying to call the above method from jQuery:

var test = [];
test.push('dog');
test.push('cat');

$container.load('MyController/DoSomething',
                { 'arr[]': test, 'someBool': true, 'someInt': 1 },
                function(response, status, xhr) {
                    // ...
                });

the array paramater is null, other params are fine. What am I doing wrong?

Chrome developer tools shows form data being submitted as

arr%5B%5D%5B%5D:dog
arr%5B%5D%5B%5D:cat
someBool:true
someInt:1

not sure whats going on there but doesn't look right to me

like image 816
fearofawhackplanet Avatar asked Oct 15 '10 12:10

fearofawhackplanet


2 Answers

If you are using jquery 1.4 you might need to set the traditional parameter to true in order to be compatible with the default model binder format in ASP.NET MVC:

var test = [];
test.push('dog');
test.push('cat');

$.ajax({
    url: 'MyController/DoSomething',
    type: 'GET',
    traditional: true,
    data: { arr: test, someBool: true, someInt: 1 },
    success: function(result) {
        $container.html(result);
    }
});

or if you prefer the .load() method:

var data = { arr: test, someBool: true, someInt: 1 };
$container.load('MyController/DoSomething', $.param(data, true), 
    function(response, status, xhr) {
    // ...
});
like image 184
Darin Dimitrov Avatar answered Sep 19 '22 18:09

Darin Dimitrov


Just remove []

{ 'arr': test, 'someBool': true, 'someInt': 1 },

Posted values (checking with Firebug).

arr[]       dog
arr[]       cat
someBool    true
someInt     1
  • Example on jsFiddle
like image 41
BrunoLM Avatar answered Sep 20 '22 18:09

BrunoLM