我正在尝试在Razor视图页面上以'foreach'语法显示分组列表。我该怎么办?
I made list like this. It works.
*before you read this: 'columnName1' is string, 'ColumnName2' is double.
//控制器---
var list = db.xxx.where(x => x.ID == 92).ToList();
return View(list);
//view---
<table class="">
@foreach (var controllerName in modle)
{
<tr>
<td>@controllerName.ColumnName1</td>
<td>@controllerName.ColumnName2</td>
</tr>
}
我尝试在下面进行分组和求和。 //控制器
var list = db.xxx.where(x => x.ID == 92).ToList();
var list1 = list
.GroupBy(y => y.columnName1)
.Select(group => new
{
columnName1 = group.Key,
columnName2 = group.Sum(x => x.columnName2)
})
.ToList();
return View(list1);
我希望显示包含分组和求和的列表。
//表
columnName1 | columnName2(sum result)
USA | 12
JAPAN | 10
答案 0 :(得分:0)
您需要为此创建一个视图模型类,因为现在您正在将一个匿名对象传递给您的视图,从技术上讲,可以使用dynamic
来实现,但是我不鼓励这样做。如果您出错了,强类型视图总是会给您带来编译时错误:
public class CountryViewModel
{
public string Name { get; set;}
public double Result {get; set;}
}
然后更改您的操作方法以将该类返回视图:
var list1 = list.GroupBy(y => y.columnName1)
.Select(group => new CountryViewModel
{
Name = group.Key,
Result = group.Sum(x => x.columnName2)
})
.ToList();
return View(list1);
在您的视图中,将模型定义更改为该视图模型类
@model Namespace.To.Your.CountryViewModel
最后,您可以在每个循环中再次使用智能感知和模型绑定:
@foreach (var item in Model)
{
<tr>
<td>@item.Name</td>
<td>@item.Result</td>
</tr>
}
答案 1 :(得分:0)
it is almost same with marco's answer.
--make a view model
public class CountryViewModel
{
public string Name { get; set;}
public double Result {get; set;}
}
--at the controller need put 'ViewModel Name'
var list1 = list.GroupBy(y => y.columnName1)
.Select(group => new CountryViewModel
{
Name = group.Key,
Result = group.Sum(x => x.columnName2)
})
.ToList();
return View(list1);
--foreach was same (i didn't need @model syntax on the top in this case.
@foreach (var item in Model)
{
<tr>
<td>@item.Name</td>
<td>@item.Result</td>
</tr>
}