Use a for-loop
instead of foreach
:
@for (var i=0;i<Model.Orders.Count();i++)
{
<div class="editor-label">
@Html.Label(Model.Orders[i].OrderName)
</div>
<div class="editor-field">
@Html.EditorFor(m=> Model.Orders[i].OrderName)
</div>
}
The reason for this issue can be easily seen on the rendered html of the foreach
approach. The names of the elements do not have an index and they all have the same name. The model binder cannot infer how to pass it to your controller. Using a for-loop
you are somewhat forcing (if that's the right term) the markup/html to have an index on your Orders
objects. Having done that, the model binder can now properly map your inputs to the Orders
field.
Oh by the way. Now that you are using a for-loop
you need to verify that your Orders
collection is not null. But I'm sure you can easily do that.