Skip to content

ViewModel in ASP.NET Core MVC

A ViewModel is a way of showing data from one or more model classes in a view. It is a class that combines properties from multiple model classes into a single class, to present joined results from more than one table.

Problem definition: We have two different model classes, an Employee model and a Department model. Our requirement is to show some properties from Employee and some from Department in a single view.

Below are four images. The first shows the Employees table in the database, the second shows the Departments table, and the third shows the join of both tables. Our requirement is to show the joined data in a view using a ViewModel.
The fourth image is the output of the ViewModel.

The image below shows the Employees table in the database.

Employees table data in SQL Server

The image below shows the Departments table in the database.

Departments table data in SQL Server

The image below shows the join of both tables in the database.

SQL join combining the Employees and Departments tables

The image below shows the final output of the ViewModel.

ViewModel output showing employee name, salary, department, HOD and location in one view

The image below shows the required packages. Install them from the NuGet Package Manager with the latest compatible version.

Required Entity Framework Core NuGet packages

After installing the packages from the NuGet Package Manager, open the appsettings.json file, add the connection string and name it DBCS, as shown in the image below.

DBCS connection string in appsettings.json

Create a model class for Employee, add its properties and use the [Key] attribute on EmployeeId, so that when we run the migration, a primary key on EmployeeId is generated in the table. Below is the Employee model class code.

public class Employee

  {

      [Key]

      public int EmployeeId { get; set; }

      public string FirstName { get; set; }

      public string LastName { get; set; }

      public string DOB { get; set; }

      public string City { get; set; }

      public int Salary { get; set; }

      public int DepartmentId { get; set; }

      public Department department { get; set; }

  }

Create a model class for Department, add its properties and use the [Key] attribute on DepartmentId, so that when we run the migration, a primary key on DepartmentId is generated in the table. Below is the Department model class code.

public class Department

   {

       [Key]

       public int DepartmentId { get; set; }

       [Display(Name ="Department Name")]

       public string DeptName { get; set; }

       [Display(Name ="Office Location")]

       public string DeptLocation { get; set; }

       [Display(Name ="Head of Department")]

       public string DeptHod { get; set; }

       public ICollection<Employee> employees { get; set; }

   }

Create a ViewModel class named EmployeeViewModel and add the properties from the Department and Employee model classes that you want to show in the view. Below is the code for EmployeeViewModel, in which FirstName, LastName and Salary come from the Employee table, and DeptName, DeptLocation and DeptHod from the Department table.

public class EmployeeViewModel

{

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int Salary { get; set; }

    public string DeptName { get; set; }

    public string DeptLocation { get; set; }

    public string DeptHod { get; set; }

}  

Create a DbContext class so that we can generate the tables in the database using code-first migrations. Write the code below in your database context class.

public class EmployeeDBContext :DbContext

{

    public EmployeeDBContext(DbContextOptions options)

    :base(options)

    {

    }

  public DbSet<Employee> Employees { get; set; }

  public DbSet<Department> Departments { get; set; }

} 
EmployeeDBContext class with Employees and Departments DbSets

After creating the model classes and the DbContext class, and adding the connection string to appsettings.json, register the services in the Program.cs file, as shown in the image and code below.

Registering EmployeeDBContext in Program.cs
using BloggingExamples.Data;

using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

builder.Services.AddDbContext<EmployeeDBContext>(options =>

options.UseSqlServer

(builder.Configuration.GetConnectionString("DBCS")));

var app = builder.Build();

if (!app.Environment.IsDevelopment())

{

  app.UseExceptionHandler("/Home/Error");

}

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(

name: "default",pattern:

"{controller=Test}/{action=ViewModelExample}/{id?}");

app.Run();

Run the migration commands below from the Package Manager Console to create the database and tables in SQL Server, as shown in the images.

Running Add-Migration FirstMigration in Package Manager Console
Running Update-Database in Package Manager Console

Now create a controller named TestController, add an action method named ViewModelExample, and create a view for this action method, as shown in the images below.

public class TestController : Controller

{

 private readonly EmployeeDBContext _db;

 public TestController(EmployeeDBContext db)

 {

   _db = db;

 }

 public IActionResult ViewModelExample()

 {

    List<EmployeeViewModel> empViews = EmployeeList().Take(10).ToList();

    return View(empViews);

 }

 public List<EmployeeViewModel> EmployeeList()

 {

    List<EmployeeViewModel> employeeViewModels = 

        new List<EmployeeViewModel>();

    var empList = from e in _db.Employees.ToList()

      join d in _db.Departments.ToList() 

      on e.DepartmentId equals d.DepartmentId 

   select new EmployeeViewModel

   {

       FirstName = e.FirstName,

       LastName = e.LastName,                           

       Salary = e.Salary,

       DeptName = d.DeptName,

       DeptHod = d.DeptHod,

       DeptLocation = d.DeptLocation

   };

   employeeViewModels = empList.ToList();

   return employeeViewModels;

}

}

In the controller code above, the EmployeeList() method returns a list of EmployeeViewModel. In the code above, a join query combines the data from the two tables and assigns it to the ViewModel.

In the view, write the HTML code, declare the model as IEnumerable<EmployeeViewModel>, loop through it and show the data in a table, as shown in the image below.

Razor view displaying the EmployeeViewModel list in a table

The final output of the view is shown in the image below. Here you can see the first name, last name, salary, department name, HOD and location in a single view.

ViewModel output showing employee name, salary, department, HOD and location in one view