Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing JSON Array from Javascript to Web API Controller method

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.

like image 657
Saravana Kumar Avatar asked Oct 21 '14 05:10

Saravana Kumar


People also ask

Why is my JSON not passing to WebAPI?

Make sure that your WebAPI service is expecting a strongly typed object with a structure that matches the JSON that you are passing. And make sure that you stringify the JSON that you are POSTing.

How do you pass an object in a JSON string?

JSON indicates values are an object using brackets { } . The following code is an example of a customer object in JSON: Notice no name is given to this object, but if you parsed it, you could still get the first and last name of your customer. Use a comma after the ending bracket and you can pass several objects in your JSON string.

How to use custom action methods in web API?

First, to use Custom Action Methods in Web API, add a web api route as: $.ajax ( { type: 'POST', url: 'http://localhost:33649/api/TestApi/TestMethod', data: {'':'hello'}, contentType: 'application/x-www-form-urlencoded', dataType: 'json', success: function (data) { console.log (data) } });

How to send JSON data to a class object?

You need to use JSON.stringify method to convert it to JSON string when you send it, And the model binder will bind the json data to your class object.


2 Answers

I ran across this thread when searching for an answer to my problem, trying to pass a list/array of object to a web api controller.

Details at this link: https://kwilson.io/blog/post-an-array-of-objects-to-webapi-using-jquery/

Change your data to be a single anonymous object instead of a raw array and it’ll work.

So in your case you might do the following for your data

data : {
                "":
                [
                    { "firstName": "John", "lastName": "Doe" },
                    { "firstName": "Anna", "lastName": "Smith" },
                    { "firstName": "Peter", "lastName": "Jones" }
                ]
            },

And in your Web API controller

[HttpPost]
public DataSet SaveDetails(List<Models.Person> obj)
{
    //save operation.    
}

This way you don't have to create another class to hold a list object like in Veera's answer.

like image 164
ascriven Avatar answered Oct 15 '22 03:10

ascriven


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

like image 40
Veera Avatar answered Oct 15 '22 04:10

Veera