How to get Ajax hosted Array in my C # controller?

I am working with ASP.NET-MVC. I am trying to publish an array in ajax, but I do not know how to get it in my controller. Here is my code:

Ajax

var lines = new Array(); lines.push("ABC"); lines.push("DEF"); lines.push("GHI"); $.ajax( { url: 'MyController/MyAction/', type: 'POST', data: { 'lines': lines }, dataType: 'json', async: false, success: function (data) { console.log(data); } }); 

Mycontroller

 public JsonResult MyAction(string[] lines) { Console.WriteLine(lines); // Display nothing return Json(new { data = 0 }); } 

Why can't I see my lines? How to properly place this array and use it in MyAction?

+7
arrays c # ajax asp.net-mvc
source share
2 answers

Set the option contentType: "application/json" and JSON.stringify your parameter:

 var lines = new Array(); lines.push("ABC"); lines.push("DEF"); lines.push("GHI"); $.ajax( { url: 'MyController/MyAction/', type: 'POST', data: JSON.stringify({ 'lines': lines }), dataType: 'json', contentType: 'application/json', async: false, success: function (data) { console.log(data); } }); 

You can also set the type of objects that you get, if that makes sense in your business case. Example:

 public JsonResult MyAction(string[] lines) { Console.WriteLine(lines); // Display nothing return Json(new { data = 0 }); } 

And something more practical with what you post:

 public class MyModel { string[] lines; } 

and finally:

 public JsonResult MyAction(MyModel request) { Console.WriteLine(string.Join(", ", request.lines)); // Display nothing return Json(new { data = 0 }); } 
+14
source share

First try changing:

 data: { 'lines': lines } 

to

 data: { lines: lines }, 

If this does not help, try using json.stringify (lines)

-one
source share

All Articles