Introducing ViewModels; A DTO And More...

Introducing ViewModels; A DTO And More...

ยท

2 min read

Software development (before code is written) is like trying to organize a wedding; there are so many decisions to be made that it can easily wear the mind thin ๐Ÿ˜…. If you've read my article on DTOs , you'll probably end up asking yourself why you need ViewModels and rightly so because they're somewhat similar, albeit with a little extra utility in ViewModels.

relatable explanation.jfif

A Relatable Explanation

ViewModels (like the name implies), is necessitated by the need to create models that can be used directly to populate pages with content that the end-users can see. DTOs are created more as an added layer that prevents direct contact between the Model (Backend) and View (frontend) while ViewModels are created specifically for interaction with the frontend.

antibes-5212942_1280.jpg

Differences Between ViewModels and DTOs

Because DTOs and ViewModels are somewhat similar, it makes sense to explain ViewModels by comparing them with the functionalities of DTOs. ViewModels typically draw data from one or more model classes and manipulate them in a bid to serve processed content to the user while DTOs are just meant to cherry-pick data from a model class and act as a gatekeeper for that model class that talks to the database directly.

DTOs were made with security in mind while ViewModels are made with the frontend user in mind, this affects how the code is written and what the code does, you find that ViewModels averagely contains more code than DTOs especially when you look at it from the perspective of MVC. To learn about the how of creating these ViewModels you should click here.

finally.jfif

Finally

A lot of experts will tell you DTOs and ViewModels should only be used for heavy projects, I feel you should use it even on small projects in order to get your hands accustomed to it, also I'm going out on a limb here but I strongly believe ViewModels are better suited to MVC projects that use Razor or Blazor pages in the frontend, Microsoft has done a lot to make the integration quite seamless.