Your view expects the model to be
IEnumerable<UserRecord>
, but your action is passing an
IEnumerable<IGrouping<string, UserRecord>>
. You need to make the types match.
One simple option would be to group the records in the view:
public ActionResult Index()
{
return View(db.UserRecords.ToList());
}
@model IEnumerable<MobileReports.Models.UserRecord>
@if (!Model.Any())
{
<p>No data uploaded yet.</p>
}
else
{
<table>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Cost</th>
</tr>
</thead>
<tfoot>
<tr>
<th scope="row">Total:</th>
<td>@Html.DisplayFor(m => m.Sum(u => u.Cost))</td>
<tr>
</tfoot>
<tbody>
@foreach (var item in Model.GroupBy(u => u.Name, (key, items) => new { Name = key, Cost = items.Sum(u => u.Cost) }))
{
<tr>
<th scope="row">@Html.DisplayFor(_ => item.Name)</th>
<th scope="row">@Html.DisplayFor(_ => item.Cost)</th>
</tr>
}
</tbody>
</table>
}
A cleaner approach would be to create a view-model to represent the grouped results. Populate the view-model in the action, and change the view to use the view-model.
public class UserCostsViewModel
{
public string Name { get; set; }
public decimal Cost { get; set; }
}
public class GroupedUserCostsViewModel
{
public IReadOnlyList<UserCostsViewModel> Items { get; set; }
public decimal Total { get; set; }
}
public ActionResult Index()
{
var source = db.UserRecords.ToList();
var items = source
.GroupBy(u => u.Name, (key, items) => new UserCostsViewModel
{
Name = key,
Cost = items.Sum(u => u.Cost)
})
.ToList();
var model = new GroupedUserCostsViewModel
{
Items = items,
Total = source.Sum(u => u.Cost)
};
return View(model);
}
@model GroupedUserCostsViewModel
@if (!Model.Items.Any())
{
<p>No data uploaded yet.</p>
}
else
{
<table>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Cost</th>
</tr>
</thead>
<tfoot>
<tr>
<th scope="row">Total:</th>
<td>@Html.DisplayFor(m => m.Total)</td>
<tr>
</tfoot>
<tbody>
@foreach (var item in Model.Items)
{
<tr>
<th scope="row">@Html.DisplayFor(_ => item.Name)</th>
<th scope="row">@Html.DisplayFor(_ => item.Cost)</th>
</tr>
}
</tbody>
</table>
}