Last post Jan 22, 2020 04:40 PM by DA924
Jan 22, 2020 04:22 PM|JORGEMAL|LINK
I know that using ViewModels is a good practice but, should I follow such a practice all over my MVC project even in very simple situations?
For example, I have a very simple DB table with the following class structure that represents it:
From these fields, I only use name and description directly because
id is an auto increment field, and date_insert and
date_update are "manually" set at the time a new record is inserted or updated. This means that such 3 fields are not typed by the user and are (virtually) never shown anywhere.
Is it a good practice to use a ViewModel with the following structure:
However, there might be certain situations where I need to display the 5 fields. An example could be a section of the system for users with administrative privileges that need to take a look at the whole picture. In this case I suppose I would use the original
class as a ViewModel.
What is a good practice? I will very much appreciate your valuable feedback.
Jan 22, 2020 04:33 PM|bruce (sqlwork.com)|LINK
its all about coupling between modules. if you pass an entity to a view, then that view is bound to the entity, rather than an interface that defines what is passed between the controller and view.
what if you decide to change the data layer from a sql to no-sql model (common now days). your entities will probably have to change. the more the users of the entities now about the structure of the data, the harder changes in that structure is.
if your database is just a backing store for the views, and not a shared production database, then the coupling is less of an issue.
Jan 22, 2020 04:40 PM|DA924|LINK
I use a view model at all times, becuase it implements seperation of concerns and binding strong type views. Myself I would just send in the 5 properties view model and just use the 2 properties mentioned as needed, which means you don't need to populate
all 5 properties if only needing two of them.
ViewModel provides us proper Separation of Concerns (SoC). The View needs to only render the single ViewModel object, and there is a specific purpose for each and every aspect of the application, which means the application will be more organized in the
code. Using ViewModel, we put our manipulation code separately in a specific place and away from the View and Controller.
But are you confusing the view model with the ORM model the persistence model, like it happens with the domain?