Search code examples
asp.net-mvcasp.net-mvc-viewmodel

Should data, that can be easily calculated on the client side, be put in the ViewModel?


Problem

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,

Options

Now I see a few approaches to filling up a ViewModel class to be consumed by the View:

  1. Put 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.

  1. Put only 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.

  1. Put 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.

Question

What's the best practice on what should the ViewModel object contain?


Solution

  • Benefits of server side:

    • Guarantees that values are correct and consistent for all users. You're not relying on the browser for calculation. Especially if they're financial and need to be accurate.
    • Guarantees performance level. You can ensure that all users will receive near-similar response times, as you're not relying on the capabilities of a user's machine to do the calculations and then manipulate the DOM to display them - some browsers are pretty slow at this. Users may have IE7 and a really slow computer. Generating the values on the server mean you can also guarantee compatibility with mobile devices and devices with script disabled.

    Benefits of client side:

    • Might save you bandwidth. This will depend on how many things the browser needs to calculate and whether the space you save exceeds the size of the script required to make it work.

    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.