CodexBloom - Programming Q&A Platform

ASP.NET Core 6: guide with Model Binding for Nested Collections in API Endpoint

👀 Views: 35 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
asp.net-core model-binding json api C#

I'm upgrading from an older version and I'm refactoring my project and Could someone explain Quick question that's been bugging me - This might be a silly question, but I'm working with an scenario with model binding when trying to post a JSON object that contains a nested collection in my ASP.NET Core 6 API......... My model looks like this: ```csharp public class Order { public int Id { get; set; } public string CustomerName { get; set; } public List<Product> Products { get; set; } } public class Product { public int ProductId { get; set; } public string ProductName { get; set; } public decimal Price { get; set; } } ``` And I have the following action method in my controller: ```csharp [HttpPost] public IActionResult CreateOrder([FromBody] Order order) { if (!ModelState.IsValid) { return BadRequest(ModelState); } // Process order... return Ok(); } ``` When I send a POST request with the following JSON payload: ```json { "Id": 1, "CustomerName": "John Doe", "Products": [ { "ProductId": 101, "ProductName": "Widget", "Price": 19.99 }, { "ProductId": 102, "ProductName": "Gadget", "Price": 29.99 } ] } ``` I'm getting a `400 Bad Request` response, and the `ModelState` behavior details indicate that the `Products` property want to be bound properly. The behavior message reads: "The JSON value could not be converted to System.Collections.Generic.List`1[Product]." I've double-checked my JSON structure and it seems to match my model. I've tried a few things: - Ensured the JSON payload is formatted correctly. - Verified that the `Products` property is nullable and initialized. - Tried using `[FromForm]` instead of `[FromBody]`, but that did not help. Is there something I'm missing or is there a known scenario with model binding for nested collections in ASP.NET Core 6? Any advice or insights would be greatly appreciated! For context: I'm using C# on Windows. What's the best practice here? I'm working on a application that needs to handle this. I'd really appreciate any guidance on this. This is part of a larger service I'm building. My development environment is CentOS. Any examples would be super helpful. This is for a desktop app running on Debian.