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?

2
  • Quick shot in the dark: Have you tried doing 'listOfStuff': listOfStuff (with '' on the key)? Commented Nov 20, 2012 at 20:48
  • Probably your array on the client side doesn't really have strings inside but numbers or whatever but not strings? Commented Nov 21, 2012 at 1:19

1 Answer 1

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
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.