0

Posting an array to web.api (api controller) does not work in it's most simple form I guess.

I have this JavaScript

var ann = { Age: 11, Name: 'Ann' };
var bob = { Age: 22, Name: 'Bob' };
var list = [ann, bob];

$.ajax({
    url: '/api/myapi/',
    data:list,
    dataType: 'json',
    type: "POST",
});

And then I have a web.api with a simple post handler

public void Post(JObject pList)
{
    //Whatever
}

If I change "data:list" with "data:ann" then everything works as expected (except bob doesn't come over of course). But the minute I put a list then it doesn't work.

I have tried to look up solutions, and some seem to serialize manually in JavaScript, is that the correct "solution"/"best practice" to this issue, or is there an easier way?

2 Answers 2

1

I think this may work for you

$.ajax({
    url: '/api/myapi/',
    data: JSON.stringify(list),
    contentType: 'application/json',
    type: "POST",
});

And your controller

public void Post(List<yourobject> list)
{
    //Whatever
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I guess that answers the question that serializing in JavaScript is the best solution. The fact that Web.api then gets a list is a clear reading improvement to what I else was trying to do
1

just change your ajax request to:

$.ajax({
    url: '/api/myapi/',
    data:list,
    traditional: true,
    dataType: 'json',
    type: "POST",
});

read this if you want some more informations: http://api.jquery.com/jQuery.param/

1 Comment

Even with trational then my JObject looks like: base {Newtonsoft.Json.Linq.JContainer} = { "undefined": [ "", "" ] }

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.