Should viewmodels contain static function methods?

If I have a Viewmodel designed to use a purpose for a view -

Is it possible to add a bunch of static methods to the viewmodel, for example - getting a list of elements (viewmodel object) by using data from db? - updating db using property in viewmodel?

I use .NET MVC and I feel that my view modes are cluttering up a bunch of static functions and update methods.

The main reason for creating a viewmodel for views was that the views began to contain a lot of functionality for which information had to be extracted from all sides. So instead, I decided to create a viewmodel to retrieve information from one place with a single call.

Am I following the example of good code? Or am I shooting in the dark?

+5
source share
2 answers

Is it possible to add a bunch of static methods in the viewmodel

No , your view model should just be a POCO containing a small (if not zero) business logic. The task only for viewing models is to move data from the controller to the view.

Generally:

  • The controller should get an instance of the model somewhere
  • it can be consumed directly, or if several models are required, combination or additional information is required (not in the model as such), then a presentation model can be created.
  • Ideally, the presentation model should be created outside the controller (maintaining the performance of the controllers), this can be achieved simply using the factory template

If you are reading the wikipedia page for the MVC template. You will notice that it is intended solely for presenting data, and not for business logic:

Model-view-controller (MVC) is a software architectural template for implementing user interfaces .

so none of the MVC objects (model, view, or controller) should contain business logic. The goal of MVC patterns is to provide data (full stop)


All of the above says that the controller includes simple business logic. However, if sites become more complex, this should be avoided for fear of creating an object.

+6
source

Am I following a good coding scheme here?

No, this is not a good model.

The main reason for creating a viewmodel for views was that the views began to contain a lot of functionality for which information had to be extracted from all sides. So instead, I decided to create a viewmodel to retrieve information from one place with a single call.

Storage functions or any logic is not the purpose of the ViewModel. It should be just a transport mechanism that stores the data transferred between the view and the controller.

Think about moving your “functionality” to “Application”, “Service” or to another level that makes sense for your application architecture.

+1
source

Source: https://habr.com/ru/post/1234195/


All Articles