Grouping orders by category in MVC4 View

2019-09-06 14:09发布

问题:

In our MVC4 application my database has an Orders table, a Products table and a Category table. Every Order has a product (plus quantity) in a foreign key relationship and the product belongs to a category with a foreign key.

So Order has an OrderId, ProductId (FK to Product), a data plus a quantity and Product has a ProductId, Name, and a CategoryId (FK to Category) and Category has a CategoryId and a Name.

Now we want to make a "shopping list" which displays the categories that are ordered during the day and display the products below the category name.

The query below based on this question does just that (except for checking the date):

public ActionResult Index()
    {
        var orders = db.Orders.Include(o => o.Product)
            .Include(o => o.Product.Category)
            .GroupBy(o => o.Product.Category.Name)
            .Select(cat => cat.FirstOrDefault());

        return View(orders.ToList());
    } 

In our view I can display the different categories by doing:

@foreach (var cat in Model) {
   <table>
       <tr>
           <td>
                @Html.DisplayFor(catName=> cat.Product.Category.Name)
           </td>
        </tr>
   </table>
}

The next step is to display the different ordered products and quantities below this in the for-loop. So that it will look like this, e.g.,:

*Fruit*
Banana x2
Apple x1

*Drinks*
Milk x1

I am struggling with this and was wondering how to do it. I hope someone can give me some pointers

回答1:

OKay, we solved the problem by making a tuple:

public ActionResult Index()
{
    var orders = db.Orders.Include(o => o.Product)
        .GroupBy(o => o.Product.Category.Name)
        .Select(cat => cat.FirstOrDefault());

    var products = db.Orders.Include(o => o.Product);

    return View(Tuple.Create(orders.ToList(), products.ToList()));
}

and in the view:

@foreach (var item in Model.Item1) {
   <table>
       <tr>
           <td>
               @Html.DisplayFor(catName => item.Product.Category.Name)
               <br />

               @foreach (var product in Model.Item2)
               {
                  if (product.Product.Category.Name == item.Product.Category.Name)
                  {
                        @Html.DisplayFor(productName => product.Product.Name)
                        @Html.DisplayFor(productName => product.Quantity) <br />
                  }
               }

           </td>
        </tr>
   </table>
}

Looks a bit crappy as of now but it works!