Show the product category as a list item in a foreach on asp.net mvc

0

I have a list in the Sales model where I usually display all the products, but now I need to display the category to which they belong, but only once, for each product category, how could I do this?

This is an example of what I want to do

Product          Quantity          Price

*Licors
Brugal           1                 500
Barcelo          15                700
*Fruits
Apple            1                 25
Banana           3                 5

This is my code, the description I want to show is in item.Product.Category.Description

<table>
  <thead>
    <tr>
      <th class="center"></th>
      <th>Serv./Prod.</th>
      <th class="center">Cant.</th>
      <th class="right">Precio</th>
    </tr>
  </thead>
  <tbody>                  
 @foreach (var item in Model.SalesDetails.OrderBy(p=>p.Product.CategoryId))
  {
    <tr>
      <td class="center"></td>
      <td class="left">   @Html.DisplayFor(modelItem => item.Product.Name)</td>

      <td class="right">     @Html.DisplayFor(modelItem => item.Quantity)</td>
      <td class="center">   @Html.DisplayFor(modelItem => item.Product.SellPrice)</td>
    </tr>
}
  </tbody>
</table>
    
asked by sGermosen 01.12.2018 в 13:46
source

1 answer

3

The first thing that you will have to change is the model to be able to define hierarchy in the data, something like being

public class CategoryModel
{
   //otras propiedades

    public List<ProductModel> Products {get;set;}
}

public class ProductModel
{
   //otras propiedades 

}

Then you can define a linq to load these classes using the group by

var model = (from p in db.Products
            group p by p.Category into g
            select new CategoryModel()
            {
              //propiedades
              Products = g.Select(x=> new ProductModel(){
                                            //propiedades
                                          })
            }).ToList();

this model will be used in the view, being able to iterate the categories and the products in a nested way with one foreach inside another

@foreach (var c in Model.Categories)
{
    <tr>
      <td colspan="3">@Html.Display(c.Name)</td>
    </tr>

    @foreach (var p in c.Products)
    {
        <tr>
          <td class="center"></td>
          <td class="left"> @Html.Display(p.Name)</td>

          <td class="right">@Html.Display(p.Quantity)</td>
          <td class="center">@Html.Display(p.SellPrice)</td>
        </tr>
    }
}
    
answered by 02.12.2018 в 21:05