0

Send a list of strings to an ASP.net core api controller with vanilla Javascript

This might sound simple but something is going wrong and i'm not sure what. I am trying to send a list of strings such as [ "something", "something else", "Another string" ] to my api post controller in ASP.Net Core.

My Controller looks like this

[HttpPost]
        public ActionResult<MyModel> Name([FromBody] List<string> list)
        {

            // Do something... 

            return NoContent();
        }

And my Javascript looks like this

async function apiCall() {

                const response = await fetch("URL", {
                    method: 'POST',
                    headers: {
                        'Content-type': 'application/json',
                        'X-CSRFToken': csrftoken
                    },
                    body: JSON.stringify({ list: [ "something", "something else", "Another string" ] })
                }}

When ever I call the apiCall() funcation it posts data to the controller but the data List is always null. How do I correctly post this data?

3
  • Your model is not an array of string, but an object with an array of string as property, all the best Commented Apr 25, 2020 at 14:28
  • Thanks it was an easy fix. When I change the body to body: JSON.stringify([ "something", "something else", "Another string" ]) It works! Commented Apr 25, 2020 at 14:32
  • sometimes happens ;) Commented Apr 25, 2020 at 14:35

1 Answer 1

1

Change

body: JSON.stringify({ list: [ "something", "something else", "Another string" ] })

To

body: JSON.stringify([ "something", "something else", "Another string" ])

And it works. I was not sending an array of strings but an object with an array of strings as a property.

Sign up to request clarification or add additional context in comments.

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.