Sungjun Andrew Kim
Sungjun Andrew Kim

Reputation: 11

How To show Grouped List on Razor View page?

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

Answers (2)

Marco
Marco

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

Sungjun Andrew Kim
Sungjun Andrew Kim

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

Related Questions