8

I work with ASP.NET-MVC. I try to post an array in ajax but I don't 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 I can't see my lines ? How to properly post this array and use it in MyAction ?

2
  • 1
    Try with traditional: true ajax settings parameter. Commented Nov 4, 2013 at 13:17
  • Try { 'lines' : JSON.stringify(lines) Commented Nov 4, 2013 at 13:20

2 Answers 2

16

Set the contentType: "application/json" option 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 you're getting if it 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're sending in:

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

Comments

-1

First, try to change:

data: { 'lines': lines }

to

data: { lines: lines },

If it won't help, try to use json.stringify(lines)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.