Ask Your Question
0

How can I send an array of objects to a controller in ASP.NET 6 (Core)?

asked 2021-07-01 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-02-18 09:00:00 +0000

lalupa gravatar image

To send an array of objects to a controller in ASP.NET 6 (Core), you can use the [FromBody] attribute in the controller method signature. Here is an example:

  1. Define the model class that represents the object in the array:
public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
}
  1. Create the controller method that accepts an array of Item objects:
[HttpPost]
public IActionResult MyControllerMethod([FromBody] Item[] items)
{
    // Do something with the items array
    return Ok();
}
  1. Send a POST request to the controller method with the array of items in the request body:
[
    { "id": 1, "name": "Item 1" },
    { "id": 2, "name": "Item 2" },
    { "id": 3, "name": "Item 3" }
]

Note that the Content-Type header of the request must be set to application/json to indicate that the data in the body is in JSON format.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-07-01 11:00:00 +0000

Seen: 12 times

Last updated: Feb 18 '22