I was struggling with this this week and Bassam's answer was the key to getting me on the right track. I have a dynamic list of inventory items that can have a quantity field. I needed to know how many of which items they selected, except the list of items can vary from 1 to n.
My solution was rather simple in the end. I created a ViewModel called ItemVM with two properties. ItemID and Quantity. In the post action I accept a list of these. With Indexing on, all items get passed.. even with a null quantity. You have to validate and handle it server side, but with iteration it's trivial to handle this dynamic list.
In my View I am using something like this:
@foreach (Item item in Items)
{
<input type="hidden" name="OrderItems.Index" value="@item.ItemID" />
<input type="hidden" name="OrderItems[@item.ItemID].ItemID" value="@item.ItemID" />
<input type="number" name="OrderItems[@item.ItemID].Quantity" />
}
This gives me a List with a 0-based Index, but iteration in the controller extracts all the necessary data from a new strongly-typed model.
public ActionResult Marketing(List<ItemVM> OrderItems)
...
foreach (ItemVM itemVM in OrderItems)
{
OrderItem item = new OrderItem();
item.ItemID = Convert.ToInt16(itemVM.ItemID);
item.Quantity = Convert.ToInt16(itemVM.Quantity);
if (item.Quantity > 0)
{
order.Items.Add(item);
}
}
You will then end up with a collection of Items that have a quantity greater than 0, and the Item ID.
This technique is working in MVC 5 utilizing EF 6 in Visual Studio 2015. Maybe this will help someone searching for this solution like I was.