I have had a look at this post and the chap there seems to want to do the same thing that I am aiming for. I have inherited this application and although I am a .NET developer the MVC stuff seems magical in comparison to other MVC frameworks in other languages which I prefer. My salient code is as follows:
public class PurchaseOrderViewModel
{
public PurchaseOrderViewModel()
{
this.PurchaseOrder = new PurchaseOrder();
}
// Some other fields here....
public PurchaseOrder PurchaseOrder { get; set; }
public IList<PurchaseOrderItem> OrderItems { get; set; }
}
The controller:
[HttpPost]
public ActionResult Details(PurchaseOrderViewModel viewModel)
{
// bunch of stuff. the viewModels.OrderItems here is null.
}
The OrderItems in the model is a ICollection<> I am converting to an IList for the iterative nature. The relevant part of the view is as follows:
@model PurchaseOrderViewModel
@for (var i = 0; i < this.Model.OrderItems.Count; i++)
{
@Html.EditorFor(m => m.OrderItems[i].Quantity);
}
So why am I not getting the OrderItems coming through? Is this to do with the fact that they are IList rather than ICollection? If so, what is the workaround?
EDIT: I have changed the view code as I left something in that I was trying before.
EDIT 2: I took into consideration current comment/answers so now I have the following changes made:
viewModel:
public ICollection<PurchaseOrderItem> PurchaseOrderItems { get; set; }
PurchaseOrderItem.cshtml: (I have left this actually as it is in code just in case):
@model Downland.Model.PurchaseOrderItem
<tr style="background-color: #fff; padding: 8px;">
<td style="text-align: left; width: 210px;">
@if (this.Model.ProductID == null)
{
<img class="viewproduct" src="~/Images/GetThumbnail/-1" alt="Product Image" style="padding: 8px;" />
}
else
{
<img class="viewproduct" src="~/Images/GetProductImage?productId=@(this.Model.ProductID)" alt="Product Image" style="padding: 8px;" />
}
</td>
<td>
@(string.IsNullOrEmpty(this.Model.SKU) ? this.Model.NonDownlandSKU : this.Model.SKU)
</td>
<td>@this.Model.ProductName</td>
<td>
@this.Model.Quantity
@Html.EditorFor(m => m.Quantity)
</td>
<td>
@string.Format("{0:C}", this.Model.PriceExVAT)
@Html.EditorFor(m => m.PriceExVAT)
</td>
<td>@string.Format("{0:C}", this.Model.VATTotal)</td>
<td>
@string.Format("{0:C}", this.Model.ItemTotal)
</td>
</tr>
View code:
@Html.EditorFor(m => m.PurchaseOrderItems);
Just another interesting point. On the GET I set the PurchaseOrder and then the PurchaseOrderItems in the view model based on the database data. On the Post it appears that we are setting the purchaseOrder in the view model with data from the database again. There are some other fields that are being set correctly in the view model based on what is passed to the post but the PurchaseOrderItems is still null.