ViewModels in ASP.Net MVC

The MVC architecture is all about separating the various layers of the applications in some logical parts. But this separation enforces some of the constraints on developers such as how to pass data from Controller to View. There are various ways to send those data to View such as using ViewData, ViewBag or TempData, the other ways is passing this data through ViewModels.

The view models group one or more entities or properties into one logical object which can be consumed by Views in order to render the contents on the View. The purpose of the View Models is to group all the necessary information required to render a view at a single place. This enforces a clear separation of Concerns, putting the data manipulation & domain entities away from the Controller & View. Using view models helps to create a good & maintainable code. Along with maintainable code, View Models are very beneficial in following cases

  1. Group all drop down related entities at a single place
  2. Master details records
  3. Pagination
  4. Dashboard details
  5. CRUD operations in which forms involves lot more controls

Although, from the above discussion it seems to be a more complex concept what View Model is, but actually it’s not. A view model is a simple C#/ VB.Net class, which contains some properties; those may involve primitive data type properties, or an entity or a set of entity.

Let’s create a ViewModel for following screen

The screen contains a text box for Name field & a drop down list for State. So ideally View Model should contain 2 properties 1 for Name & other for text box. So while rendering a view the ViewModel should be

This class will serve as a view Model when the view is rendered. So the controller will contain following code to render this form.

The above code will return a new form with State drop down list filled with 1 value NY. If we look at the AccountRegistrationGetViewModel carefully, you may notice [Required] attribute. This is one of the Data Annotations attribute supported by ASP.Net. They help us to validate the input data.

Now let’s create a view

It will generate a View which will contain following markup

But after validations user should be able to view the errors also we should accept these values at the Action Methods into a ViewModel. So let’s design that ViewModel.

So now when data is posted to the server in a Controller, we should catch this data in AccountRegistrationPostViewModel  . Also In order to show errors we need to add a property, as follows.

So our controller method will be So if validations are exploited these will be shown to user as below.

                 This is how we can use ViewModels. Initially it may look complex to create separate view Model for each function but later when it come to maintain the code, you will find it very very easy to fix the changes rather than striking you head on hardcoded strings.

You can find the source here.