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 Examples. Please read our previous 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 the ASP.NET Core MVC application. So in simple words, we can say that a ViewModel in ASP.NET Core MVC is a model that contains more than one model data required for a particular view. Combining multiple model objects into a single view model object provides us with better optimization.

In ASP.NET Core MVC, a ViewModel is a design pattern used to represent the data and behavior needed for a specific view. ViewModels are particularly useful when you need to display data in a view that comes from multiple sources, requires formatting, or needs additional logic before being presented. The ViewModel acts as an intermediary between the view and the underlying data models, ensuring that the view has exactly the data it needs in a structured and easily consumable format.

Understanding the ViewModel in ASP.NET Core MVC:

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

ViewModel in ASP.NET Core MVC Application

Let’s 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’s basic details, whereas 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 the page header and page title in the view. If this is our requirement, then we need to create a view model, say StudentDetailsViewModel, and that view model will contain both the models (Student and Address) and properties to store the page title and page header.

Creating the Required Models:

We will work with the same example we worked on in our previous article. First, modify the Student.cs class file, which is present within the Models folder of your application, as follows. This model will represent the basic information of a student, such as a Name, Branch, Section, etc.

namespace FirstCoreMVCWebApplication.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 into it.

namespace FirstCoreMVCWebApplication.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, it’s the 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 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. Copy and paste the following code once you create the StudentDetailsViewModel.cs class file.

using FirstCoreMVCWebApplication.Models;

namespace FirstCoreMVCWebApplication.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, and 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 to follow this naming convention to organize view models.

Creating Student Controller:

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

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

namespace FirstCoreMVCWebApplication.Controllers
{
    public class StudentController : Controller
    {
        public ViewResult 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 view model contains all the data required by the 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 of 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 into it.

@model FirstCoreMVCWebApplication.ViewModels.StudentDetailsViewModel
@{
    Layout = null;
}
<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 the @Model property.

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

ASP.NET Core MVC ViewModel with Examples

ViewModels are especially valuable in scenarios where:
  1. Aggregation of Data: A view requires data from multiple data models or sources. Instead of cluttering the view with data retrieval logic, you can create a ViewModel that combines and organizes the required data.
  2. Data Formatting and Display Logic: The data from models needs to be transformed, formatted, or adapted for presentation. ViewModel can include methods and properties that encapsulate this logic.
  3. Reducing Coupling: ViewModel separates the view’s needs from the specifics of your data models, which can help reduce coupling and make your application more maintainable.
  4. Data Annotations: ViewModels can be used to add data validation attributes and annotations specific to the presentation layer without affecting the underlying data models.

ViewModels play a significant role in keeping the separation of concerns and promoting a clean architecture in your ASP.NET Core MVC applications. They ensure that the presentation layer remains decoupled from the data layer and provide a clear structure for handling view-specific data and logic.

In the next article, I am going to discuss ASP.NET Core MVC TempData with Examples. Here, in this article, I try to explain the ViewModel in ASP.NET Core MVC Application with Examples. I hope you understand the need and use of ASP.NET Core MVC ViewModel with Examples.

5 thoughts on “ViewModel in ASP.NET Core MVC”

  1. No need for these two lines in the StudentController code:
    ViewBag.Title = “Student Details Page”;
    ViewBag.Header = “Student Details”;

  2. As Ahmed has already pointed above, setting the values for ViewBag.Title and ViewBag.Header is not required as we are using strongly typed model. They are not being used anyway.

    Further, can you please write a guide on using a ViewModel for a form and submitting it back to the controller?

    Thanks.

  3. Ephraim Fuchs

    Between this lesson and the last, the StudentId changed from a string to an int.
    Because of this, the HomeController.cs generates a compile time error.

Leave a Reply

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