CodexBloom - Programming Q&A Platform

ASP.NET Core MVC: implementing Model Binding for Nested Objects in Form Submission

👀 Views: 17 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-16
asp.net-core mvc model-binding C#

After trying multiple solutions online, I still can't figure this out. After trying multiple solutions online, I still can't figure this out... I'm sure I'm missing something obvious here, but I'm working with an scenario with model binding in my ASP.NET Core MVC application when submitting a form that includes nested objects. I've defined a view model that contains a list of items, each of which is a custom class. However, when I submit the form, the list is coming back as null in my action method. Here's my view model: ```csharp public class OrderViewModel { public string CustomerName { get; set; } public List<ItemViewModel> Items { get; set; } } public class ItemViewModel { public string ProductName { get; set; } public int Quantity { get; set; } } ``` In my view, I'm using a form to display these items: ```html <form asp-action="SubmitOrder" method="post"> <input type="text" name="CustomerName" /> <div id="items"> @for (int i = 0; i < Model.Items.Count; i++) { <div> <input type="text" name="Items[@i].ProductName" /> <input type="number" name="Items[@i].Quantity" /> </div> } </div> <button type="submit">Submit</button> </form> ``` When I submit this form, the `Items` property in my `OrderViewModel` is null in the controller action: ```csharp [HttpPost] public IActionResult SubmitOrder(OrderViewModel model) { // model.Items is null here if (model.Items == null) { ModelState.AddModelError(string.Empty, "Items are required."); } // Process the order } ``` I've tried ensuring that the names of the inputs match the expected model binding format, but I'm still not getting the expected results. Could anyone guide to understand why `Items` is null? What am I missing here? Additionally, I've confirmed that the model is being passed correctly from the view to the action method, but the nested list seems to be the only thing not binding properly. I'm using ASP.NET Core 3.1. Any insights or solutions would be appreciated! Any help would be greatly appreciated! This is part of a larger CLI tool I'm building. I'd really appreciate any guidance on this. What's the best practice here? I'm on Windows 10 using the latest version of C#. Any ideas how to fix this?