Showing totals in an asp.net MVC list view?
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
It开发者_开发百科em 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:
Public Class MyViewModel
Public Property Columns As List(Of ColInfo)
Public Property Items As List(Of RowItem)
End Class
Public Class ColInfo
Public Property Id As Guid
Public Property Name As String
Public Property ColTotal As Integer
End Class
Public Class RowItem
Public Property Name As String
Public Property ColValues As Dictionary(Of Guid, Integer)) ' Value lookup for each column
Public Property RowTotal As Integer
End Class
(Note, I added a "Row Total" to my example as well, in addition to the column totals.)
I would advocate using jQuery for this. You can write a simple function that iterates over all the cell values in a table column, totals them and then set's the total as the value in the respective cell.
This is preferred since today the number of client machines with javascript disabled is next to none, hence it will always work. Also, it keeps your model classes a little bit cleaner and also when scaling it will reduce load (albeit little load) from the web server.
Also, as the number of columns increase the required jQuery would stay the same while the amount of additional data being passed to the client would only increase with a server side approach.
Many people say that View logic should be minimal, but this ideally refers to logic that has some server side annotation such as User Roles, Authentication, Access Control, Conditional Rendering, etc. I use a lot of jQuery in my Views and it keeps my application speedy as well as rich in UI.
精彩评论