ViewModel in ASP.NET MVC

ViewModel in ASP.NET MVC Application

In this article, I am going to discuss ViewModel in ASP.NET MVC application with an example. Please read our previous article before proceeding to this article where we discussed Strongly Typed Views in ASP.NET MVC application.

What is a ViewModel in ASP.NET MVC?

In ASP.NET MVC application, a single model object may not contain all the necessary data required for a view. For example, a view may require different model data. Then in such situations like this, we need to use the concept ViewModel.

A ViewModel in ASP.NET MVC application is a model which contains more than one model data required for a particular view. As this model is specific for a particular view, we call this as ViewModel in ASP.NET MVC.

Understanding the ViewModel in ASP.NET MVC:

Let us have a look at the following diagram which shows the visual representation of a view model in MVC application.

ViewModel in ASP.NET MVC Application

Let say we want to display the employee details in a webpage. And in our application, we have two different models to represent the employee data. The Employee Model is used to represent the basic details of an employee whereas the Employee Address model is used to represent the employee.

Along with the above two models to represent the employee data, we also required some static information like page header and title in the view. In order to achieve this, here we need to create a view model such as EmployeeDetailsViewModel. It is this view model which is going to contain both Employee and Employee Address models as well as properties to store the title and header of the webpage.

Creating the Required Models:

First, create a class file with the name Employee.cs within the Models folder. The Employee model is going to represent the basic information such as name, gender, department, etc. Once you create the Employee.cs class file, then copy and paste the below code in it.

namespace FirstMVCDemo.Models
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string Department { get; set; }
        public decimal Salary { get; set; }
        public int AddressId { get; set; }
    }
}

Now, we need to create the Address model to represent the employee Address such as City, State, Country, etc. So, create a class file with the name Address.cs within the Models folder and then copy and paste the following code in it.

namespace FirstMVCDemo.Models
{
    public class Address
    {
        public int AddressId { get; set; }
        public string Country { get; set; }
        public string State { get; set; }
        public string City { get; set; }
        public string Pin { get; set; }
    }
}
Creating the View Model in ASP.NET MVC:

Now it’s time to create the required View Model to store the required data which is required for a particular view. The View Model that we are going to create will represent the Employee Model + Employee Address Model + Some additional properties like title and page header.

In ASP.NET MVC application, you can create the View Models anywhere within your project, but it is always a good programming practice to create all the View Models within a special folder called ViewModels.

So first create a folder with the name ViewModels and then create a class file with the name EmployeeDetailsViewModel.cs within the ViewModels folder. Then copy and paste the following code in it.

using FirstMVCDemo.Models;
namespace FirstMVCDemo.ViewModels
{
    public class EmployeeDetailsViewModel
    {
        public Employee Employee { get; set; }
        public Address Address { get; set; }
        public string PageTitle { get; set; }
        public string PageHeader { get; set; }
    }
}

Here we created the view model class with the name as EmployeeDetailsViewModel. Here the word Employee represents the Controller name, the word Details represent the action method name. As it is a view model so we prefixed the word ViewModel. Although it is not mandatory to follow this naming convention, I personally feel it good to follow this naming convention.

Creating Employee Controller:

Right click on the Controllers folder and then add a new MVC 5 Empty controller with the name EmployeeController.cs and then copy and paste the following code in it.

using FirstMVCDemo.ViewModels;
using FirstMVCDemo.Models;
using System.Web.Mvc;

namespace FirstMVCDemo.Controllers
{
    public class EmployeeController : Controller
    {
        public ViewResult Details()
        {
            //Employee Basic Details
            Employee employee = new Employee()
            {
                EmployeeId = 101,
                Name = "Dillip",
                Gender = "Male",
                Department = "IT",
                Salary = 10000,
                AddressId = 1001
            };

            //Employee Address
            Address address = new Address()
            {
                AddressId = 1001,
                City = "Bhubaneswar",
                State = "Odisha",
                Country = "India",
                Pin = "755019"
            };

            //Creating the View model
            EmployeeDetailsViewModel employeeDetailsViewModel = new EmployeeDetailsViewModel()
            {
                Employee = employee,
                Address = address,
                PageTitle = "Employee Details Page",
                PageHeader = "Employee Details",
            };

            //Pass the employeeDetailsViewModel to the view
            return View(employeeDetailsViewModel);
        }
    }
}

As you can see in the above code, here we are passing the employee details view model as a parameter to the view. And one more thing you need to notice that now we are not using any ViewData or ViewBag within our Details action method.

Creating the Details View:

First, add a folder with the name Employee within the Views folder of your application. Once you add the Employee Folder, then you need to add a view file with the name Details.cshtml within the Employee folder and then copy and paste the following code in it.

@model FirstMVCDemo.ViewModels.EmployeeDetailsViewModel

@{ 
    Layout = null;
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>@Model.PageTitle</title>
</head>
<body>
    <h1>@Model.PageHeader</h1>
    <div>
        EmployeeID : @Model.Employee.EmployeeId
    </div>
    <div>
        Name : @Model.Employee.Name
    </div>
    <div>
        Gender : @Model.Employee.Gender
    </div>
    <div>
        Department : @Model.Employee.Department
    </div>
    <div>
        Salary : @Model.Employee.Salary
    </div>

    <h1>Employee Address</h1>
    <div>
        City : @Model.Address.City
    </div>
    <div>
        State : @Model.Address.State
    </div>
    <div>
        Country : @Model.Address.Country
    </div>
    <div>
        Pin : @Model.Address.Pin
    </div>
</body>
</html>

Now, the Details view has access to the EmployeeDetailsViewModel object. By using the @model directive, we set EmployeeDetailsViewModel as the Model for our Details view. Then we access Employee, Address, PageTitle and PageHeader properties using the @Model property.

Now run the application, and navigate to the “/Employee/Details” URL and you will see the output as expected as shown in the below image. 

ViewModel in ASP.NET MVC

In the next article, I am going to discuss TempData in ASP.NET MVC application with an example.

SUMMARY

In this article, I try to explain the ViewModel in ASP.NET MVC application. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *