The role of ViewModel

We all know that a ViewModel is a container-type class that represents only the data we want to display on our web page. In any standard MVC-based ASP.NET application, the ViewModel is instantiated by the Controller in response to a GET request using the data fetched from the Model; once built, the ViewModel is passed to the View, where it's used to populate the page contents/input fields.

The main reason for building a ViewModel instead of directly passing the Model entities is that it only represents the data that we want to use, and nothing else; all the unnecessary properties that are in the model domain object will be left out, keeping the data transfer as lightweight as possible. Another advantage is the additional security it gives, since we can protect any field from being serialized and passed through the HTTP channel.

In a standard Web API context, where the data is passed using conventions via serialized formats such as JSON or XML, the ViewModel can be easily replaced by a JSON-serializable dynamic object created on the fly, such as this:

var response = new { 
Id = "1",
Title = "The title",
Description = "The description"
};

This approach is often viable for small or sample projects, where creating one (or many) ViewModel classes can be a waste of time. That's not our case, though conversely, our project will greatly benefit from having a well-defined, strongly-typed ViewModel structure, even if they will all be eventually converted into JSON strings.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.133.233