I have a table built out in a Razor view that goes like so:
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.column1)</td>
...
...
</tr>
}
I want to add a summary of the table at the end, something like:
<tr>
<td>@Model.Sum(a => a.column1)</td>
...
...
</tr>
That actually works but it doesn’t use my data annotations since I’m not using DisplayFor(). I tried placing the Model.Sum within a DisplayFor() but the code doesn’t work. Can anyone point me towards a solution?
You could write an HTML helper that examined the property lambda, performed the sum() and utilized your data annotations.
View Model
View
Helper Extension
This is far from perfect. An improvement would be to allow any type to be summed without having to provide a different method for every summable type.