Send array to MVC via JSON?

I am trying and trying to send an array via JSON to an MVC controller action.

Here is what I have and what I tried ...

//Get checked records var $checkedRecords = $(':checked'); //eg 3 rows selected = [input 4, input 5, input 6] //Have tried following: sendingVar: $checkedRecords.serializeArray(); // gives array of 0's sendingVar: JSON.stringify($checkedRecords); // gives "{\"length\":1,\"prevObject\":{\"0\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"context\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"length\":1},\"context\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"selector\":\":checked\",\"0\":{}}"...wtf //Post $.post(url, { sendingVar: sendingVar }, function(data) {alert(data); }); 

How can I do it?

edit: for those who suggest sending $checkedRecords "as is" from the top line - this does not work. I get a strange exception somewhere in the jquery structure: (

 uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://.../.../.../jquery-1.4.4.min.js :: <TOP_LEVEL> :: line 141" data: no] 

which, I think, means that he is trying to assign null to what he cannot.

Edit: I am using MVC2 not 3

Edit2: After @Monday's answer, the problem is how I built the array, for example [input 4, input 5, input 6] , and not [4,5,6] - any ideas on how I can just get the values ​​in an array instead?

Edit3: Stop voting to duplicate if it is not. Did you really read my problem or read related issues? this is another problem.

@Daveo:

I don't want to create an overriding user attribute just to send an array from JSON, which is ridiculous , as we already covered in this question, this is not necessary.

MVC3 - irrelevant

+7
source share
2 answers

Here is my demo, use mvc2, hope some help ~

The key to success is traditional

set traditional to true

 $(function(){ var a = [1, 2]; $.ajax({ type: "POST", url: "<%= ResolveUrl("~/Home/PostArray/") %>", data: {orderedIds: a}, dataType: "json", traditional: true, success: function(msg){alert(msg)} }); }) 

Since jquery 1.4, this parameter exists, since the mechanism for serializing objects in query parameters has changed.

and action ~

 [HttpPost] public ActionResult PostArray(int[] orderedIds) { return Content(orderedIds.Length.ToString()); } 
+22
source

you can also use JSON.stringyfy to send data as a string, then use the JavaScriptSerializer class to retrieve the data.

In C #, the code to get the data would look like this:

 JavaScriptSerializer js = new JavaScriptSerializer(); js.Deserialize<T>(string paramiter); 
0
source

All Articles