ViewModel in ASP.NET Core MVC

ViewModel in ASP.NET Core MVC Application

In this article, I am going to discuss ViewModel in ASP.NET Core MVC application with an example. Please read our previous article before proceeding to this article where we discussed Strongly Typed View in ASP.NET Core MVC application. As part of this article, we are going to discuss the following pointers.

  1. What is a View Model in ASP.NET Core?
  2. Why do we need the View Model?
  3. How to implement the View Model in ASP.NET Core Application?
What is a ViewModel in ASP.NET Core MVC?

In real-time applications, a single model object may not contain all the data required for a view. In such situations, we need to use ViewModel in ASP.NET Core MVC application. So in simple words, we can say that a ViewModel in ASP.NET Core MVC is a model which contains more than one model data required for a particular view. Combining multiple model objects into a single view model object provides us better optimization.

Understanding the ViewModel in ASP.NET Core MVC:

The following diagram shows the visual representation of a view model in ASP.NET Core MVC application.

ViewModel in ASP.NET Core MVC Application

Let say we want to display the student details in a view. We have two different models to represent the student data. The Student Model is used to represent the student basic details where the Address model is used to represent the address of the student. Along with the above two models, we also required some static information like page header and page title in the view. If this is our requirement then we need to create a view model let say StudentDetailsViewModel and that view model will contain both the models (Student and Address) as well as properties to store the page title and page header.

Creating the Required Models:

First, create a class file with the name Student.cs within the Models folder of your application. This is the model which is going to represent the basic information of a student such as a name, branch, section, etc. Once you create the Student.cs class file, then copy and paste the following code in it.

namespace FirstCoreMVCApplication.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public string Branch { get; set; }
        public string Section { get; set; }
        public string Gender { get; set; }
    }
}

Next, we need to create the Address model which is going to represent the Student 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 FirstCoreMVCApplication.Models
{ 
    public class Address
    {
        public int StudentId { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
        public string Pin { get; set; }
    }
}
Creating the View Model:

Now we need to create the View Model which will store the required data that is required for a particular view. In our case its student’s Details view. This View Model is going to represent the Student Model + Student Address Model + Some additional data like page title and page header.

You can create the View Models anywhere in your application, but it is recommended to create all the View Models within a folder called ViewModels to keep the things organized.

So first create a folder at the root directory of your application with the name ViewModels and then create a class file with the name StudentDetailsViewModel.cs within the ViewModels folder. Once you create the StudentDetailsViewModel.cs class file, then copy and paste the following code in it.

using FirstCoreMVCApplication.Models;
namespace FirstCoreMVCApplication.ViewModels
{
    public class StudentDetailsViewModel
    {
        public Student Student { get; set; }
        public Address Address { get; set; }
        public string Title { get; set; }
        public string Header { get; set; }
    }
}

We named the ViewModel class as StudentDetailsViewModel. Here the word Student represents the Controller name, the word Details represent the action method name within the Student Controller. As it is a view model so we prefixed the word ViewModel. Although it is not mandatory to follow this naming convention, I personally prefer it to follow this naming convention to organize view models.

Creating Student Controller:

Right-click on the Controllers folder and then add a new class file with the name StudentController.cs and then copy and paste the following code in it.

using FirstCoreMVCApplication.Models;
using FirstCoreMVCApplication.ViewModels;
using Microsoft.AspNetCore.Mvc;

namespace FirstCoreMVCApplication.Controllers
{
    public class StudentController : Controller
    {
        public ViewResult Details()
        {
            ViewBag.Title = "Student Details Page";
            ViewBag.Header = "Student Details";

            //Student Basic Details
            Student student = new Student()
            {
                StudentId = 101,
                Name = "Dillip",
                Branch = "CSE",
                Section = "A",
                Gender = "Male"
            };

            //Student Address
            Address address = new Address()
            {
                StudentId = 101,
                City = "Mumbai",
                State = "Maharashtra",
                Country = "India",
                Pin = "400097"
            };

            //Creating the View model
            StudentDetailsViewModel studentDetailsViewModel = new StudentDetailsViewModel()
            {
                Student = student,
                Address = address,
                Title = "Student Details Page",
                Header = "Student Details",
            };

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

As you can see, now we are passing the view model as a parameter to the view. This is the view model which contains all the data required by Details view. As you can notice, now we are not using any ViewData or ViewBag to pass the Page Title and Header to the view instead they are also part of the ViewModel which makes it a strongly typed view.

Creating the Details View:

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

@model FirstCoreMVCApplication.ViewModels.StudentDetailsViewModel

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>@Model.Title</title>
</head>
<body>
    <h1>@Model.Header</h1>
    <div>
        StudentId : @Model.Student.StudentId
    </div>
    <div>
        Name : @Model.Student.Name
    </div>
    <div>
        Branch : @Model.Student.Branch
    </div>
    <div>
        Section : @Model.Student.Section
    </div>
    <div>
        Gender : @Model.Student.Gender
    </div>

    <h1>Student 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 StudentDetailsViewModel object that we passed from the controller action method using the View() extension method. By using the @model directive, we set StudentDetailsViewModel as the Model for the Details view. Then we access Student, Address, Title, and Header using @Model property.

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

ViewModel in ASP.NET Core MVC application

In the next article, I am going to discuss the Routing view in ASP.NET Core MVC application with an example. Here, in this article, I try to explain the ViewModel in ASP.NET Core MVC application with an example. I hope you understood the need and use of ViewModel in ASP.NET Core MVC Application.

Leave a Reply

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