1

How can I post an array of elements to a controller action using jQuery Ajax post.

This is how I am trying, but my controller recieving a null array.

function dipatchAllocations() {
            // unSelected is an array of items of type int.
            if (unSelected.length == 0) {
                alert("Please select a line item to be dispatched.");
                return;
            }
            debugger;
            $.ajax({
                type: 'POST',
                url: '/Batch/SetToDispatch',
                data: '{ "allocationId[]" : "[' + unSelected + ']","batchId" : "' + @Model.Id + '" }',
                contentType: "application/json; charset=utf-8",
                traditional: true,
                success: updateView,
                error: errorInSubscribing
            });
        };

And this is my controller

[HttpPost]
public ActionResult SetToDispatch(long[] allocationId,long batchId)
{   
  // Perform some action here
   return View("_ReadyToDispatchItems",model);
}

Can somebody advice me what I am missing.

Thanks

2
  • Have you tired removing "[]" after allocationId Commented Nov 29, 2012 at 5:14
  • Can you show unSelected declaration? Commented Nov 29, 2012 at 5:28

3 Answers 3

1

Try this:

var data = { allocationId : unSelected, batchId : @Model.Id };
$.ajax({
                type: 'POST',
                url: '/Batch/SetToDispatch',
                data: JSON.stringify(data),
                contentType: "application/json; charset=utf-8",
                traditional: true,
                success: updateView,
                error: errorInSubscribing
            });
Sign up to request clarification or add additional context in comments.

Comments

0

Your json syntax seems to be off, no [] required after allocationId[] See: http://www.w3schools.com/json/json_syntax.asp for the syntax on arrays

Comments

0

You can simply give the data to controller as query string it will work

 $.ajax({
            type: 'POST',
            url: '/Batch/SetToDispatch/' + unSelected + ',' + batchId
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            traditional: true,
            success: updateView,
            error: errorInSubscribing
        });

Its comma seperated you can split it in controller and use it. Hope it helps

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.