Say I want to display some values on a website following good MVC principles (as well as ASP.NET MVC guidelines but the problem is very likely not tied to a specific MVC framework), e.g.,:
A - number of type A items
,
B - number of type B items
,
T - number of all items
(a total count),
A/T % - percentage of type A items
,
B/T % - percentage of type B items
,
Now I see a few approaches to filling up a ViewModel class to be consumed by the View:
all 6 values
in the ViewModel and just display them where necessary, no client side calculations whatsoever,as we do not accept any client side calculations.
A
, B
in the ViewModel, client calculates the total (A+B) and the percentage (A/T % and B/T %),as we want to send as little data in the ViewModel, through the network, as possible.
A
, B
, T
in the ViewModel, client calculates the percentage (A/T % and B/T %),as we consider these values to be another visual representation of the data it has already got.
What's the best practice on what should the ViewModel object contain?
Benefits of server side:
Benefits of client side:
As you can see, I'm leaning towards the server side option. If you have a lot of calculation to do, you could always cache the results to reduce the required resources. Even then, you need to weigh up the size of the cache vs the CPU overhead for calculations.