Back to: ASP.NET Core Tutorials For Beginners and Professionals
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.
- What is a View Model in ASP.NET Core?
- How Do We Implement the View Model in the ASP.NET Core Application?
- Benefits of Using View Model in ASP.NET Core MVC?
What is a ViewModel in ASP.NET Core MVC?
A View Model in ASP.NET Core MVC is a class that represents the data and logic required by a view. It is specifically designed to serve the needs of the user interface and does not necessarily map directly to the domain model or database entities. The primary purpose of a View Model is to encapsulate all the data that the view needs to render, making it easier to pass this data from the controller to the view. It acts as an intermediary between the controller and the view, encapsulating the data displayed or edited on the view.
In Real-Time Applications, a single model object may not contain all the data required for a view. We must use a View Model in the ASP.NET Core MVC application in such situations. In simple words, a View Model in ASP.NET Core MVC is a model that contains more than one model data required for a particular view.
How Do We Implement the View Model in an ASP.NET Core Application?
To implement a view model in ASP.NET Core MVC, follow these steps:
- Define the View Model: Create a class that includes properties relevant to the view’s needs.
- Populate the View Model in the Controller: In your controller, populate the view model from the domain model or other data sources.
- Pass the View Model to the View: Pass the populated view model to the view from the controller using the View overloaded method, which takes the model object as a parameter.
- Use the View Model in the View: Access the view model’s properties in the view using Razor syntax.
Let us understand the View Model in ASP.NET Core MVC with an Example. The following diagram shows the visual representation of a view model in the 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 use the same example that we have been worked so far. First, modify the Student.cs class file, which is present within the Models folder of your application, as follows. This model will represent a student’s basic information, 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, 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 copy and paste the following code.
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, 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 Titles and Headers.
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 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 it 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. As you can see in the Details action method, we populate the StudentDetailsViewModel with the required data and then send 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, we are now passing the view model as a parameter to the view. This view model contains all the data required by the Details view. 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. 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. As shown in the image below, you will see the expected output on the webpage.
Benefits of View Model in ASP.NET Core MVC:
With View Model in ASP.NET Core MVC, we will get the following benefits:
- Strongly Typed: Unlike ViewData or ViewBag, which are dynamic and loosely typed, a ViewModel is a strongly typed object. This means it has a specific, predefined structure with properties of defined types. This strong typing ensures compile-time type checking, reducing the risk of runtime errors and making the codebase more robust and maintainable.
- Separation of Concerns: View models separate the presentation layer from the business logic and data access layers. This means views are not dependent on the database schema or domain logic, promoting cleaner and more maintainable code.
- UI Customization: They allow customization of the data presentation for specific views without impacting the underlying data models.
- Data Aggregation: View models can aggregate data from multiple domain models or services into a single object that is easy for the view to consume.
- Security: Using view models can improve security by ensuring that only the necessary data is exposed to the view. It prevents over-posting attacks where users could potentially submit additional, unwanted fields through form submissions.
- Optimized Data Loading: View models can help optimize data transfers between the server and client by including only the data necessary for the view, reducing payload sizes and load times.
In the next article, I will discuss ASP.NET Core MVC TempData with Examples. In this article, I try to explain the View Model in an ASP.NET Core MVC Application with examples. I hope you understand the need and use of the ASP.NET Core MVC ViewModel with Examples.
No need for these two lines in the StudentController code:
ViewBag.Title = “Student Details Page”;
ViewBag.Header = “Student Details”;
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.
Yes. There is no need. Thanks for identifying the issue. We have corrected this.
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.
We have corrected the example. Please check now.