ViewModel in ASP.NET Core MVC

ViewModel in ASP.NET Core MVC Application

In this article, I will discuss ViewModel in ASP.NET Core MVC Application with Examples. Please read our previous article discussing Strongly Typed View in ASP.NET Core MVC Application. As part of this article, we will discuss the following pointers.

  1. What is a View Model in ASP.NET Core?
  2. Why do we need the View Model?
  3. How do you implement the View Model in the ASP.NET Core Application?
  4. When should you use the View Model in ASP.NET Core MVC?
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. We must use ViewModel in the ASP.NET Core MVC application in such situations. 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.

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 student’s address. Along with the above two models, we also required some static information in the view, like the page header and page title. 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, representing 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 to store the data required for a particular view. In our case, it’s the student’s Details view. This View Model will 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, Student represents the Controller name, and Details represents the action method name within the Student Controller. As it is a view model, 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 named StudentController.cs, and copy and paste the following code into it. As you can see in the Details action method, we are populating the StudentDetailsViewModel with the required data and then sent it to the corresponding view.

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 expected output on the webpage, as shown in the image below. 

ASP.NET Core MVC ViewModel with Examples

When should you use ViewModel in ASP.NET Core MVC?

The ViewModel acts as a model specifically designed for a view, containing only the data needed for that view. Here are some common situations where using a ViewModel is beneficial:

  • Data Aggregation: When a view requires data from multiple sources or models. A ViewModel can aggregate this data, presenting a single object to the view. This approach simplifies the view and makes it more maintainable.
  • Data Formatting and Presentation Logic: If the data needs to be formatted or processed for display purposes (like date formatting, concatenating strings, etc.), a ViewModel can encapsulate this logic, keeping the view clean and focused on presentation.
  • Complex Data Binding: In scenarios where the view has complex data binding requirements that do not map directly to your domain models. A ViewModel can reshape the data in a more suitable form for binding in the view.
  • Validation: For views that require specific validation logic that doesn’t apply to your domain models. ViewModels can define validation rules specific to the view’s requirements using attributes.
  • Decoupling: To maintain a clean separation of concerns between the UI and the business logic. ViewModels helps decouple your views from your business logic and data access layers.
  • Performance Optimization: In cases where fetching the entire domain model might be expensive in terms of performance. A ViewModel can contain just the necessary data, reducing the server and network load.
Best Practices
  • Single Responsibility: Each ViewModel should be specific to a view or a set of closely related views. Avoid a ‘one size fits all’ approach.
  • Avoid Business Logic: ViewModels should not contain business logic. They are for transferring data between the controller and the view.
  • Mapping: When dealing with complex domain models, consider using a mapping library like AutoMapper to simplify the conversion between domain models and ViewModels.
  • Naming Convention: Name your ViewModels in a way that makes their purpose clear. For example, ProductDetailViewModel is more descriptive than ProductModel.

In the next article, I will discuss ASP.NET Core MVC TempData with Examples. 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 *