我想打印从控制器收到的viewbag但我不能,我在控制器中的代码在这里:
var qry = from c in db.Customers
join o in db.Orders on id equals o.CustomerID
where id == o.CustomerID
select new {o.OrderID ,o.OrderDetails};
ViewBag.OrdersForUser = qry.ToList();
我认为的打印代码是:
@foreach (var order in ViewBag.OrdersForUser)
{
@order
}
现在的印刷文本是:
{ OrderID = 1, OrderDetails = System.Collections.Generic.HashSet`1[FinalProject.Models.OrderDetail] }
OrderID的类型是int,OrderDeatils的类型是ICollection 我想打印哈希集中的数据(而不是像现在这样的decleration),并将Order Id拆分到其他空间。
答案 0 :(得分:1)
ViewBag是一种动态类型。并且您分配了一个匿名类型,然后您无法在视图端获取其类型。
<强>控制器强>
var qry = from c in db.Customers
join o in db.Orders on id equals o.CustomerID
where id == o.CustomerID
// in this line, what is the type of list ? You should define its type
// for example:
select new SomeType{OrderId = o.OrderID ,OrderDetails = o.OrderDetails}
//select new {o.OrderID ,o.OrderDetails};
ViewBag.OrdersForUser = qry.ToList();
然后在你的
中查看强>
@foreach (var order in (List<SomeType>)ViewBag.OrdersForUser)
{
@order
}
评论后
或者,如果您的实体之间存在关系定义,则只能获得以下订单详细信息:
<强>控制器:强>
ViewBag.OrdersForUser = db.OrderDetails.Where(d=>d.Order.CustomerId == id);
查看:
@foreach (var orderDetail in (List<OrderDetail>)ViewBag.OrdersForUser)
{
@orderDetail.Order.xxx
}