If I am using the ASP.net MVC standard list view is there an easy way to create totals in the view? I can copy the standard list code in here but I am not doing anything fancy here.
I “could” do the totals as another object in the model going to the view but then it would still need to somehow be handled in the view.
What I have now looks sort of like:
ColA colb ColC
Item 1 1 2
Item 2 1 2
What I want is:
ColA colb ColC
Item 1 1 2
Item 2 1 2
Total 3 2 4
While it might be trivial to sum up these totals right in the view, I have always opted to put these totals right in my ViewModel for the view. This gives me the ability to unit test that my totals are accurate. If the logic for the totaling was done in the view, there would be no easy way to test such a thing. This keeps the view logic simple and limited to displaying values, not doing the “logic” necessary to sum values up.
Taking this to the next level, what if the rules for a “total” were that negative amounts don’t “count” toward the total? Then the view would be responsible for not only knowing how to sum the items, but also needs to be aware of the “don’t count negative values” business rule. I find it’s best to let the server do as much of the work as it can, and making the view as “simple” (thin) as possible.
In your example, I may have a ViewModel that looks like:
(Note, I added a “Row Total” to my example as well, in addition to the column totals.)