Reputation: 11
I'm trying to show grouped list with 'foreach' syntax on Razor view page. How can I do?
I made list like this. It works.
*before you read this: 'columnName1' is string, 'ColumnName2' is double.
//controller---
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>
}
I try to do below for grouping and summing. //controller
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);
I expect to show list with grouping and summing.
//table
columnName1 | columnName2(sum result)
USA | 12
JAPAN | 10
Upvotes: 0
Views: 2155
Reputation: 23937
You need to create a view model class for this, since right now, you are passing an anonymous object to your view, which technically is possible using dynamic
, but I don't encourage that. A strongly typed view will always give you compile time errors, if you go wrong:
public class CountryViewModel
{
public string Name { get; set;}
public double Result {get; set;}
}
Then change your action method to return that class to the view:
var list1 = list.GroupBy(y => y.columnName1)
.Select(group => new CountryViewModel
{
Name = group.Key,
Result = group.Sum(x => x.columnName2)
})
.ToList();
return View(list1);
In your view change your model definition to that viewmodel class
@model Namespace.To.Your.CountryViewModel
And finally you can use intellisense and model binding in your for each loop again:
@foreach (var item in Model)
{
<tr>
<td>@item.Name</td>
<td>@item.Result</td>
</tr>
}
Upvotes: 1
Reputation: 11
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>
}
Upvotes: 0