The error occurs because your view is using a model that is typeof ShirtOrdersViewModel
and its layout is calling a partial that expects List<Order>
. Because the layout has
@Html.Partial("_ItemsCartPartial", (Model as List<Order>))
you are attempting to cast the model which is ShirtOrdersViewModel
to List<Order>
which fails and the result of that is the same as
@Html.Partial("_ItemsCartPartial", null)
When you pass null
as the model, the method uses the ViewDataDictionary
of the main view and so the method now passes ShirtOrdersViewModel
to a partial expecting List<Order>
, hence the exception.
Your current implementation means that your layout can only be used by a view whose model is List<Order>
(or is a model that derives from a BaseModel which contains a property List<Order>
in which case you could use @Html.Partial("_ItemsCartPartial", Model.MyListOfOrdersProperty)
). However that would be the wrong approach in your case, and instead you should create a method that returns a PartialView
of the orders, for example
[ChildActionOnly]
public ActionResult Orders()
{
List<Order> orders = .... // get orders for the current user
return PartialView("_Orders", orders);
}
and the _Orders.cshtml
file would have @model List<Order>
and the code to display them. Then in the layout, render the results of the partial using
@{ Html.RenderAction("Orders", yourControllerName); }