0

Possible Duplicate:
Send array to MVC controller via JSON?

I haven't really found a good solution to this so far.

My javascript/jQuery and I try to send the data using ajax.

    var val = new Array();
    $( ':checkbox:checked' ).each( function ( i )
    {
        console.log( $( this ).val() );
        val[i] = $(this).val();
    });
    removeSelected(val);


function removeSelected(listOfStuff)
{
    $.ajax({
        url: '@(Url.Action("removeSelected"))',
        type: 'POST',
        data: { listOfStuff: listOfStuff },
        dataType: 'json',
        success: function ( return_data )
        {
            $( ":checkbox:checked" ).closest('tr').remove();
        }
    });

And my controller. The array comes in as null.

    [HttpPost]
    public bool removeSelected ( string[] listOfStuff )
    {
       //do stuff
    }

Any suggestions?

Community
  • 1
  • 1
user1608132
  • 301
  • 5
  • 13
  • Quick shot in the dark: Have you tried doing `'listOfStuff': listOfStuff` (with '' on the key)? – khellang Nov 20 '12 at 20:48
  • Probably your array on the client side doesn't really have strings inside but numbers or whatever but not strings? – Kath Nov 21 '12 at 01:19

1 Answers1

1

You could try the traditional: true suggestion referenced in this answer, which, from the API reference, is:

A Boolean indicating whether to perform a traditional "shallow" serialization.

That change would look like:

$.ajax({
    url: '@(Url.Action("removeSelected"))',
    type: 'POST',
    traditional: true,
    data: { listOfStuff: listOfStuff },
    dataType: 'json',
    success: function ( return_data )
    {
        $( ":checkbox:checked" ).closest('tr').remove();
    }
});

In addition, may I make a small suggestion for your code? I would change this:

var val = new Array();
$( ':checkbox:checked' ).each( function ( i )
{
    console.log( $( this ).val() );
    val[i] = $(this).val();
});

to:

var val = []; // use this array notation
$(':checkbox:checked').each(function ()
{
    console.log($(this).val());
    val.push($(this).val()); // use push() instead of an index
});
Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194