0

This is my Linq in Controller

 List<ProfitsModel> prof = new List<ProfitsModel>();

            var categories =
                from p in prof
                group p by p.IdCategory.Name into g
                select new { Category = g.Key, TotalUnitsInStock = g.Sum(p => p.Value) };

            return View(categories);

how to see this select in my view?

Krasimir
  • 259
  • 4
  • 9
  • 28

2 Answers2

1

Looks like your building a collection of Anonymous object. What you should do is, Create a ViewModel and use that in your LINQ query by updating the projection part. So that instead returning a list of anonymous items, it returns a list of your viewmodel class instances

public class StockDetail
{ 
  public string CategoryName { set;get;}
  public int TotalItems { set;get;}
}

Now in your GET action method, update the projection part of the LINQ expression and load the result into a list of StockDetail

public ActionResult GetCategories()
{
   List<ProfitsModel> prof =GetCollectionOfProfitsModelFromSomewhere();
   var items= from p in prof
                group p by p.IdCategory.Name into g select new StockDetail
                   { Category = g.Key, TotalUnitsInStock = g.Sum(p => p.Value) };
  return View(items);
}

Make your view strongly typed to a collection of StockDetails

@model List<StockDetail>

@foreach(item in Model)
{
  <p>@item.Category </p>
  <p>@item.TotalUnitsInStock.ToString()</p>

}
Shyju
  • 214,206
  • 104
  • 411
  • 497
0

Bind a model to the view and add a list or enumerable property to the model. You can then foreach over the enumerable directly in the view and render out each item within a defined piece of HTML structure.

If your model is an anonymous type then you could can use ViewBag/ViewData to store the results.

SpaceBison
  • 3,704
  • 1
  • 30
  • 44