Managing Data With ViewModel In ASP.NET MVC

This article will tell you almost everything about ViewModel in ASP.NET MVC. I am writing this article to tell you the basic to advanced foremost concepts about ways to manage the data and organize the code in ASP.NET MVC. Stay tuned for my coming articles.

I would strongly recommend reading my previous articles, which will be defining the basic concepts of ASP.NET MVC, as listed below.

Read this article, check the code after downloading, and then feel free to give your feedback.

The topics to be covered are,

  1. ViewModel and its usage
  2. How data can be managed with ViewModel
  3. Where we should use ViewModel
  4. Understanding ViewModel with a practical example

Introduction and Background

The concept of ViewModels is not only for ASP.NET MVC. It is also used in MVC, MVP, and MVVM design patterns. In this article, you’ll learn what are ViewModels and how can we manage and clean the code with ViewModels.

What ViewModel is

In ASP.NET MVC, ViewModels are used to shape multiple entities from one or more models into a single object. This conversion into single object provides us better optimization. You can see the concept of ViewModel in the image below.

Managing Data with ViewModel In ASP.NET MVC 

As you can see, if we want to display more than one Model into a single View, we have to pass a ViewModel to that View, so that we can take benefits of both the models into a single object. So, we have to use ViewModel for  better performance of sources.

How data is managed with ViewModel

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.

So, it provides us a better SoC and makes our code more maintainable. It also makes our code more testable because unit testing means testing the small units, and it is easier to test if we separate the manipulation logic in a separate ViewModel.

Where we should use ViewModel?

We can use ViewModel in the following scenarios,

  • Managing or creating dropdown lists for a specific entity
  • Creating Master-Details View in data-driven websites
  • Used in showing shopping carts on the website
  • Used in Pagination
  • Used in a website to show User profile widget
  • Used to make Dashboards for integrating multiple data into one place
  • Used as an Aggregate Root to make reports in Domain Driven Design (DDD)

These are the complex scenarios in which ViewModel can be used for better maintainability, reliability, and testability of code.

Understanding ViewModel with a practical example

Let’s take an example in which there is a View for showing a list of books. And, we also want to show the list of customers who rented these books. We don’t have any relationship between books and the customers so, the purpose is to only show the data of both classes together. And as you know, there will be separate model classes for Book and Customer, and we can’t pass both models into a single View. Hence, we have to make a ViewModel.

Let’s create a project with the name ViewModelsDemo.

Managing Data with ViewModel In ASP.NET MVC 

Then, select Empty, check MVC, then click OK.

Managing Data with ViewModel In ASP.NET MVC 

Now, let’s create the model classes for both - Book and Customer.

Managing Data with ViewModel In ASP.NET MVC 

Give that class the name “Book” and click OK.

Managing Data with ViewModel In ASP.NET MVC 

And then, write the following code into it.

  1. namespace ViewModelsDemo.Models  
  2. {  
  3.     public class Book  
  4.     {  
  5.         public int BookId { get; set; }  
  6.         public string BookName { get; set; }  
  7.     }  
  8. }  

Now, repeat the same procedure to make another class named as “Customer”. Write the following code into it.

  1. namespace ViewModelsDemo.Models  
  2. {  
  3.     public class Customer  
  4.     {  
  5.         public int CustomerId { get; set; }  
  6.         public string CustomerName { get; set; }  
  7.    
  8.     }  
  9. }  

Now, make a Controller to handle the HTTP requests.

Managing Data with ViewModel In ASP.NET MVC 

Then, select “MVC 5 Controller – Empty”.

Managing Data with ViewModel In ASP.NET MVC 

And give a name as “HomeController”.

Managing Data with ViewModel In ASP.NET MVC 

Place the following code into it.

  1. using System.Collections.Generic;  
  2. using System.Web.Mvc;  
  3. using ViewModelsDemo.Models;  
  4.    
  5. namespace ViewModelsDemo.Controllers  
  6. {  
  7.     public class HomeController : Controller  
  8.     {  
  9.         public ActionResult Index()  
  10.         {  
  11.             var Book = new List<Book>()  
  12.             {  
  13.                 new Book {BookName = "Programming in C#"},  
  14.                 new Book {BookName = "Programming in C++"},  
  15.                 new Book {BookName = "Programming in Java"}  
  16.             };  
  17.    
  18.             var Customer = new List<Customer>()  
  19.             {  
  20.                 new Customer {CustomerName = "Zain"},  
  21.                 new Customer {CustomerName = "Hassan"},  
  22.             };  
  23.    
  24.             return View();  
  25.         }  
  26.     }  
  27. }  

In the above code, we’ve populated the model classes with data. Now it is time to make ViewModel. Conventionally create a folder into the project, and give it name “ViewModels”. Look, ViewModel is simply a class having “ViewModel” as a suffix. So, create a class and give it a name as “CustomerViewModel”. Place the following code into it.

  1. using System.Collections.Generic;  
  2. using ViewModelsDemo.Models;  
  3.    
  4. namespace ViewModelsDemo.ViewModels  
  5. {  
  6.     public class CustomerViewModel  
  7.     {  
  8.         public List<Book> Books { get; set; }  
  9.         public List<Customer> Customers { get; set; }  
  10.     }  
  11. }  

Now, come back to the Controller and make an object of CustomerViewModel. Then, pass this object to the View. The complete code of HomeController carefully.

  1. using System.Collections.Generic;  
  2. using System.Web.Mvc;  
  3. using ViewModelsDemo.Models;  
  4. using ViewModelsDemo.ViewModels;  
  5.    
  6. namespace ViewModelsDemo.Controllers  
  7. {  
  8.     public class HomeController : Controller  
  9.     {  
  10.         public ActionResult Index()  
  11.         {  
  12.             var Book = new List<Book>()  
  13.             {  
  14.                 new Book {BookName = "Programming in C#"},  
  15.                 new Book {BookName = "Programming in C++"},  
  16.                 new Book {BookName = "Programming in Java"}  
  17.             };  
  18.    
  19.             var Customer = new List<Customer>()  
  20.             {  
  21.                 new Customer {CustomerName = "Zain"},  
  22.                 new Customer {CustomerName = "Hassan"},  
  23.                 new Customer {CustomerName = "Syed"}  
  24.             };  
  25.    
  26.             var CustomerViewModel = new CustomerViewModel  
  27.             {  
  28.                 Books = Book,  
  29.                 Customers = Customer  
  30.             };  
  31.    
  32.             return View(CustomerViewModel);  
  33.         }  
  34.     }  
  35. }  

Now, make a View named as “Index” in the “Home” folder of Views folder and place the code.

  1. @model ViewModelsDemo.ViewModels.CustomerViewModel  
  2. @{  
  3.     ViewBag.Title = "Index";  
  4. }  
  5.    
  6. <h2>List of Books and list of Customers together</h2>  
  7.    
  8. <h4>List of Books</h4>  
  9. <ul>  
  10.     @foreach (var book in Model.Books)  
  11.     {  
  12.         <li>  
  13.             @book.BookName;  
  14.         </li>  
  15.     }  
  16. </ul>  
  17.    
  18.    
  19. <h4>List of Customers</h4>  
  20. <ul>  
  21.     @foreach (var customer in Model.Customers)  
  22.     {  
  23.         <li>  
  24.             @customer.CustomerName;  
  25.         </li>  
  26.     }  
  27. </ul>  

Simply build and run the application. You would see the following output.

Managing Data with ViewModel In ASP.NET MVC 

Summary

In this article, you have learned what the ViewModel is, what are its uses, and how we can organize and maintain our code using ViewModel. In the end, you have seen the practical example of ViewModel. Hope it will help you.

Conclusion

I hope this article has helped you in understanding the concepts of ViewModel in ASP.NET MVC. Stay tuned for my next articles. If you have any query, please feel free to contact me in the comments section. Also, do provide the feedback whether positive or negative. It will help me to make my articles better and increase my enthusiasm to share my knowledge.