davidcoder
davidcoder

Reputation: 938

asp.net mvc model binder with child collections

I'm learning ASP.NET MVC and having a problem with saving a model as below:

Orders -> OrderItems

In my Create view , I will add some items into Order and when I press submit, I want the items data bind to model.OrderItems. How can I achieve this ?

    [HttpPost]
    public ActionResult Create(OrderViewModel model)
    {
       ...............
       //iterate item list and add to main order
       foreach (var item in model.OrderItems) <~ this is what I'm trying to do
        {

        }
       ...............
    }

Thanks a lot.

Upvotes: 3

Views: 1102

Answers (1)

Joey Gennari
Joey Gennari

Reputation: 2361

If they're sequential, you can create an index on each of your inputs:

<input type="text" name="OrderItems[0].Name" value="Stuff" />
<input type="text" name="OrderItems[0].Price" value="5.00" />
...
<input type="text" name="OrderItems[1].Name" value="OtherStuff" />
<input type="text" name="OrderItems[1].Price" value="15.00" />

Or you'll need to provide an index:

<input type="hidden" name="OrderItems.Index" value="@item.ItemId" />
<input type="text" name="OrderItems[@item.ItemId].Name" value="Stuff" />
<input type="text" name="OrderItems[@item.ItemId].Price" value="5.00" />

Upvotes: 5

Related Questions