ViewModel in ASP.NET Core MVC

ViewModel is way of representing the data on View from one or more model classes. It Model Class used for defining the properties from multiple Model classes and used into a single class for presenting the joined results from more than one tables.

Problem Defination :- We have two different model classes ,one is Employee model and second one is Department model class , here our requirement to show some properties from Employee and some properties from Department to represent it on a View from controller.

Below we have attached Four Images in which first images you can see the Employees table in Database , In second image you can see the Departments table in the Database and third Image is the Joins of the both table , now our requirement is to show the joined data into the view using ViewModel.
Below fourth image is the OutPut for ViewModel.

Below Image is for Employees table in Database

Image is not available

Below Image is for Departments table in Database.

Image is not available

Below Image is for joins of data from both the tables in Database.

Image is not available

Below Image is the final outcome of the ViewModel.

Image is not available

In Below Image required packages are shown and you can install it from nuget package manager with latest/compatible version.

Image is not available

After installing the packages from Nuget Packet Manager ,open the appsettings.json file and write the connection string into it and named it as DBCS as shown in below image.

Image is not available

Create a Model Class for Employee and write down the properties for Employee in model class and use [Key] attribute for EmployeeId so that when we run the migration a primary key with EmployeeId will be genearate into 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 and write down the properties for Department in model class and use [Key] attribute for DepartmentId so that when we run the migration a primary key with DepartmentId will be genearate into 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 employees { get; set; }
    }
                 
                

Create a ViewModel Class for EmployeeViewModel and in which write down the selected properties from Department model class that you want to present and also write the selected properties from Employee model class that you need to represent on view. Below is the code for EmployeeViewModel in which FirstName,LastName and Salary are from Employee table and DeptName,DeptLocation,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 Model Class for DBContext so that we can generate the tables in the database using the code first migration. Write down the below code in your database context model class.


public class EmployeeDBContext :DbContext
{
    public EmployeeDBContext(DbContextOptions options)
    :base(options)
    {
    }
  public DbSet Employees { get; set; }
  public DbSet Departments { get; set; }
} 
Image is not available

After creating the Model Classes ,DbContext Class and write a connection string in appsettings.json file add the services into the Program.cs file as shown in below image and below code block.

Image is not available

using BloggingExamples.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext(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 from package manager console to create tables and database in Sql server using the below commands shown in the images.

Image is not available
Image is not available

Now create a controller and named it as Test Controller and write the action method into it and named it as ViewModelExample and then create a view for this action method as shown in below images.


public class TestController : Controller
{
 private readonly EmployeeDBContext _db;
 public TestController(EmployeeDBContext db)
 {
   _db = db;
 }
 public IActionResult ViewModelExample()
 {
    List empViews = EmployeeList().Take(10).ToList();
    return View(empViews);
 }
 public List EmployeeList()
 {
    List employeeViewModels = 
        new List();
    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 above controller code we have written a Method EmployeeList() ,it is returning the list of EmployeeViewModel. In the above code we used Join Query to join the data from two tables and assign that data into the ViewModel.

In the created view write down the html code and specify the Model as EmployeeViewModel in IEnumberable List and loopthrough it and present the data into the table as shown in below image.

Image is not available

The final output of the view is shown in the below image.Here you can see the FirstName,LastName,Salary,Department Name,Hod and Location in a single view.

Image is not available

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.