且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在asp.net MVC列表视图中显示总计?

更新时间:2023-11-29 22:33:28

虽然在视图中对这些总数进行汇总可能很简单,但我始终选择将这些总数正确地放入视图的ViewModel中.这使我能够对我的总数是否准确进行单元测试.如果在视图中完成了合计逻辑,就没有简单的方法可以测试这种情况.这样可以使视图逻辑变得简单,并且仅限于显示值,而无需执行将值求和的逻辑".

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.

在您的示例中,我可能有一个如下所示的ViewModel:

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.)