Search code examples
c#asp.netasp.net-mvchashsetviewbag

Viewbag , Printing data from hashset


i want to print the viewbag recieved from the controller but i cant, my code in the controller is here:

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();

the printing code in my view is :

@foreach (var order in ViewBag.OrdersForUser)
{
   @order
}

the printed text right now is:

{ OrderID = 1, OrderDetails = System.Collections.Generic.HashSet`1[FinalProject.Models.OrderDetail] }

the type of OrderID is int, the type of OrderDeatils is ICollection i want to print the data in the hash set (and not the decleration like now) , and to split the Order Id into other space.


Solution

  • ViewBag is a dynamic type. And you assign an anonymous type, then you cant get its type in view side.

    controller

    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();
    

    and then in your

    view

    @foreach (var order in (List<SomeType>)ViewBag.OrdersForUser)
    {
       @order
    }
    
    • List that you return from controller, should not be anonymous type. (select new SomeType)
    • In view, you should define viewbag type. (List)ViewBag.OrdersForUser)

    AFTER COMMENT

    Or if there is relation definitions between your entities, you can get only order details like following :

    controller:

    ViewBag.OrdersForUser = db.OrderDetails.Where(d=>d.Order.CustomerId == id);
    

    view :

    @foreach (var orderDetail in (List<OrderDetail>)ViewBag.OrdersForUser)
    {
       @orderDetail.Order.xxx
    }