Send Javascript Array for Controller via POST

2

I'm trying to send Array of int from JavaScript to Controller via POST . See my array:

console.debug(itens);

Array [ 1, 2 ]

I'm trying to send it as follows:

$.post('@Url.Action("MinhaAction", "MeuController")', { MeuParametro : itens })

MyController looks like this:

[HttpPost]
public ActionResult MinhaAction(int[] MeuParametro)

But when debugging, I have received null in my controller, because instead of sending:

MeuParametro : [1,2]

JavaScript has been sent:

MeuParametro[] : "1"
MeuParametro[] : "2"

I tried using JSON.parse () :

 $.post('@Url.Action("MinhaAction", "MeuController")', { MeuParametro : JSON.parse(itens) })

And it has only worked when I have only one item in my array, but when I have two or more (as is my case), the following error is returned:

  

SyntaxError: JSON.parse: unexpected non-whitespace character after   JSON data at line 1 column 3 of the JSON data jquery-1.8.2.js line   578 > eval: 126: 71

Could anyone help me with this?

    
asked by anonymous 13.10.2015 / 14:50

3 answers

1

It worked by following the hint of these answers:

Using:

jQuery.ajaxSettings.traditional = true;

The problem is that the settings are global. If you want something different in another post, this will cause problems. Home So I could usually use:

$.post('@Url.Action("MinhaAction", "MeuController")', { MeuParametro : itens })
    
13.10.2015 / 16:18
1

Good morning, Grande also tries to create a pattern in your variable items, more or less like itens.id, so in case when you send pro controller it will identify a json:

itens:{
    {"id":"1"},
    {"id":"2"}
}
    
13.10.2015 / 15:49
1

You can do this as follows:

var countryArray = [1,2,3,4];

    $.ajax({
        type: "POST",
        url: "../Home/SaveTable",
        contentType: 'application/json',
        data: JSON.stringify({ MeuParametro : countryArray}),
    });

That is, instead of doing JSON.parse(array) you will have to do JSON.stringify({ MeuParametro : countryArray}

Difference between JSON.parse and JSON.stringify

According to Ben Smith's 'Basic Json' "There is a stringify method that generates JASON serialized from a given." In a nutshell, JSON.parce converts serialized JSON into JavaScript values "

Link book

Important links:

link

p>

p>     
13.10.2015 / 19:45