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

后端 未结 2 1517
孤城傲影
孤城傲影 2021-01-12 14:15

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 Arra         


        
2条回答
  •  -上瘾入骨i
    2021-01-12 14:25

    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 });
    }
    

提交回复
热议问题