问题
I've searched many posts on SO and still not sure what I did wrong here. I have a model
for "Order" which includes a <list>
of "OrderItem"
public class Order
{
public int OrderId { get; set; }
public int CustId { get; set; }
public DateTime OrderDate { get; set; }
public int OrderType { get; set; }
...
...
public List<OrderItem> OrderItems = new List<OrderItem>();
}
public class OrderItem
{
public string ProductCode { get; set; }
public decimal RetailPrice { get; set; }
public string ProductQuantity { get; set; }
}
In my view, which is strongly typed to the Order model, I am using an Editor Template to display the order items
@model FTG.Models.Order
@Html.EditorFor(x => x.OrderItems)
and the editor template seems to assign a proper name for the model binding to occur:
input type="number" id="OrderItems_0__ProductQuantity" name="OrderItems[0].ProductQuantity"...
input type="number" id="OrderItems_1__ProductQuantity" name="OrderItems[1].ProductQuantity"...
But my model comes back to the controller with count=0
for the list. The rest of the model looks fine, I just can't get the values from the list of orderitems.
Does anyone know what I am doing wrong, or what I am missing?
回答1:
I think your model class is missing a property for the child list. Try adding a property for the OrderItems list.
回答2:
OrderItems is a field, not a property. You need to make it a property with a getter and setter, then in your constructor you create the empty list and assign it to the property.
来源:https://stackoverflow.com/questions/15095513/asp-net-mvc-model-binding-fails-for-list-items-in-editor-template