Using an IEnumerable within Dynamic Typ

2019-08-18 06:11发布

问题:

var s = myInventoryEntities.p_Forms().Select(i => new  { i.Customer, i.Order_ID }).Distinct().ToList();

ViewBag.MyData = s;

return View();

this gives me

    { Customer = "Bob", Order_ID = 2644550 }

In my razor code

i traverse the data

@foreach ( var x in @ViewBag.MyData){
x.Customer // Does not exist! :(
}

Please help!

'object' does not contain a definition for 'Customer'

回答1:

ViewBag data's life time is very limited. Are you sure you are coming to this view from the same action method where you set the ViewBag data ?

Suggestion : Try to Avoid Dynamic types liek ViewData/ViewBag. Sticking to Strongly typed makes your code much better readable/ maintainable.

If your Domain object and What you want to display is same, do not bother about creating a ViewModel. else create a viewmodel

public class CustomerOrder
{
  public string CustomerName
  public int OrderID { set;get;}
  //other properties as relevant (to the view)
}

and return that instead of the ViewBag

public ActionResult GetOrders()
{

  var s = myInventoryEntities.p_Forms().
          Select(i => new  CustomerOrder {
                                           CustomerName= i.Customer, 
                                           OrderID=i.Order_ID
                                         }).Distinct().ToList();
  return View(s);
}

And in the view

@model IList<CustomerOrder>
@foreach ( var x in Model)
{
   <p>@x.Customer</p>
}