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 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 ViewModels are and how we can 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 a single object provides us with better optimization. You can see the concept of ViewModel in the image below.

ViewModel

As you can see, if we want to display more than one Model in a single View, we have to pass a ViewModel to that View, so that we can take the benefits of both 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 with proper Separation of Concerns (SoC). The View needs to render only 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 with 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 a 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. 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.

ViewModelsDemo

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

MVC

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

Model classes

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

Book

Then, write the following code into it.

namespace ViewModelsDemo.Models
{
    public class Book
    {
        public int BookId { get; set; }
        public string BookName { get; set; }
    }
}

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

namespace ViewModelsDemo.Models
{
    public class Customer
    {
        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
    }
}

Now, make a Controller to handle the HTTP requests.

HTTP requests

Then, select “MVC 5 Controller – Empty”.

MVC 5 controller

And give a name as “HomeController”.

Home controller

Place the following code into it.

using System.Collections.Generic;
using System.Web.Mvc;
using ViewModelsDemo.Models;

namespace ViewModelsDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var Book = new List<Book>()
            {
                new Book {BookName = "Programming in C#"},
                new Book {BookName = "Programming in C++"},
                new Book {BookName = "Programming in Java"}
            };

            var Customer = new List<Customer>()
            {
                new Customer {CustomerName = "Zain"},
                new Customer {CustomerName = "Hassan"},
            };

            return View();
        }
    }
}

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 the name “ViewModels”. Look, ViewModel is simply a class having “ViewModel” as a suffix. So, create a class and give it the name “CustomerViewModel”. Place the following code into it.

using System.Collections.Generic;
using ViewModelsDemo.Models;

namespace ViewModelsDemo.ViewModels
{
    public class CustomerViewModel
    {
        public List<Book> Books { get; set; }
        public List<Customer> Customers { get; set; }
    }
}

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.

using System.Collections.Generic;
using System.Web.Mvc;
using ViewModelsDemo.Models;
using ViewModelsDemo.ViewModels;

namespace ViewModelsDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var Book = new List<Book>()
            {
                new Book {BookName = "Programming in C#"},
                new Book {BookName = "Programming in C++"},
                new Book {BookName = "Programming in Java"}
            };

            var Customer = new List<Customer>()
            {
                new Customer {CustomerName = "Zain"},
                new Customer {CustomerName = "Hassan"},
                new Customer {CustomerName = "Syed"}
            };

            var CustomerViewModel = new CustomerViewModel
            {
                Books = Book,
                Customers = Customer
            };

            return View(CustomerViewModel);
        }
    }
}

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

@model ViewModelsDemo.ViewModels.CustomerViewModel
@{
    ViewBag.Title = "Index";
}

<h2>List of Books and list of Customers together</h2>

<h4>List of Books</h4>
<ul>
    @foreach (var book in Model.Books)
    {
        <li>
            @book.BookName
        </li>
    }
</ul>

<h4>List of Customers</h4>
<ul>
    @foreach (var customer in Model.Customers)
    {
        <li>
            @customer.CustomerName
        </li>
    }
</ul>

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

Run application

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 queries, please feel free to contact me in the comments section. Also, do provide feedback whether positive or negative. It will help me to make my articles better and increase my enthusiasm to share my knowledge.


Similar Articles