Passing JSON Array from Javascript to Web API Controller method

Saravana Kumar picture Saravana Kumar · Oct 21, 2014 · Viewed 18.5k times · Source

I was not able to get the JSON array parameters in web api controller method (SaveDetails).
Here are my code.

JavaScript Code:

  $.ajax(
    {
        url  : "api/Test/SaveDetails",
        type : "POST",
        data : {
                    "employees":
                    [
                        { "firstName": "John", "lastName": "Doe" },
                        { "firstName": "Anna", "lastName": "Smith" },
                        { "firstName": "Peter", "lastName": "Jones" }
                    ]
                },
        success: function (data) {alert("success");},
        error: function () {alert("Error");}
    })
    

Controller method

[HttpPost]
public DataSet SaveDetails(Models.Person[] obj)
{
    //save opertion.    
}

Model Method:

 public class Person
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}

What are the changes to be made to get the JSON array parameters in web api method.

Answer

Veera picture Veera · Oct 24, 2014

Try the following code:

Declare the model method as follows:

public class Models.employees
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}

public class Models.RootObject
{
    public List<employees> employees { get; set; }
}

Controller:

[HttpPost]
public DataSet SaveDetails([FromBody]RootObject Person)
{
    //save opertion.    
}

Here comes the expected Result: Output