在MVC4视图中按类别对订单分组 [英] Grouping orders by category in MVC4 View
问题描述
在我们的MVC4应用程序中,我的数据库有一个Orders表,一个Products表和一个Category表.每个订单都有一个具有外键关系的产品(加数量),并且该产品属于具有外键的类别.
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.
因此,订单具有OrderId,ProductId(从FK到Product),数据和数量,而Product具有ProductId,Name和CategoryId(从FK到Category),而Category具有CategoryId和Name.
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>
}
下一步是在for循环中显示以下不同的订购产品和数量.这样看起来像这样:
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
推荐答案
好的,我们通过创建一个元组来解决该问题:
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()));
}
并在视图中:
@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!
这篇关于在MVC4视图中按类别对订单分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!