Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this query:
C#
var binstock = db.Bin_Material
	 .GroupBy(m => m.Material.Name)
	 .Select( g => new{Name = g.Key,Total = g.Sum(m => m.Qty)});
ViewBag.BinStock = binstock;
return.View();

When I access the result via the ViewBag in the .cshtml:
HTML
@foreach (var item in @ViewBag.BinStock)
 {
  <tr>
    <th>@item.Name</th>		
  </tr>
 }


I get an error: 'object' does not contain a definition for 'Name'

But I can see the "Name" and "Total" names in the intellisense.

What am I missing here?
Posted

In your select you defined anonymous objects. That's good, but than you pass the enumeration of anonymous objects to dynamic one that is passed to the view engine. The dynamic one has knowledge over it's fields so @ViewBag.BinStock will work. But the items in it are just anonymous objects - outside their context (anonymous types have method scope[^]), thus you can't access their fields directly. So: you either use named types, or play around with the dynamic types starting from here: Using Anonymous Types Outside of Local Context with Dynamic Keyword[^], or use reflection. But I suggest you take the first approach.
 
Share this answer
 
v3
Cheers, here is what I did:

C#
//Helper Class
public class BinStockModel
{
  public string Name { get; set; }
  public double Total { get; set; }
}


and then in my controller:
C#
var binstock = db.Bin_Material
    .OrderBy(m=>m.Material.Name)
    .GroupBy(m => m.Material.Name)
    .Select(
        g => new {
	  Name = g.Key,
	  Total = g.Sum(m => m.Qty)
	});
var res = new List<binstockmodel>();
foreach (var item in binstock)
{
    res.Add(new BinStockModel{ Name = item.Name, Total = (double)item.Total });
}
return View(res);</binstockmodel>

And then in my View:
HTML
@model IEnumerable<storemanager.models.binstockmodel>
@foreach (var item in @Model)
{
    bintotal = bintotal + @item.Total;
    <tr>
        <th>@item.Name</th>
	<td style="text-align: right;">@item.Total</td>
    </tr>
}
</storemanager.models.binstockmodel>


Worked a charm.
 
Share this answer
 
Comments
Zoltán Zörgő 24-Jun-13 7:08am    
Actually this should work also:
var binstock = db.Bin_Material
.OrderBy(m=>m.Material.Name)
.GroupBy(m => m.Material.Name)
.Select(
g => new BinStockModel() {
Name = g.Key,
Total = g.Sum(m => m.Qty)
});

return View(binstock);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900