Models in ASP.NET Core MVC

Models in ASP.NET Core MVC Application

In this article, I will discuss the Models in ASP.NET Core MVC Applications with Examples. Please read our previous article discussing Controllers in ASP.NET Core MVC Applications. We will work with the same example we created in our Controller in ASP.NET Core MVC article.

What is a Model in ASP.NET Core MVC?

A model is a class with .cs (for C#) extension with properties and methods. Models are used to set or get the data. If your application does not have data, then there is no need for a model. If your application has data, then you need a model.

The Models in ASP.NET Core MVC Application contain a set of classes representing the domain data (you can also say the business data) and logic to manage the domain/business data. So, in simple words, we can say that the Model is the component in the MVC Design pattern that is used to manage the data, i.e., the state of the application in memory. The Model represents a set of classes used to describe the application’s validation, business, and data access logic. 

If you are working with any Web Application that is based on the MVC Design Pattern, then in that MVC Application, three things are common, i.e., Model, View, and Controller. The Controllers are used to manage the overall flow of the MVC Application. Models are responsible for storing the data that is used on Views. Views are basically the HTML Pages that get rendered into the client’s browser. In the browser, we generally perform two operations. First, we display the data to the user; second, we get the data from the user. For both these operations, models are used.

Where will we Store the Models in the MVC Application?

It is not mandatory, but storing all the Model classes within the Models folder is a good programming practice. Even though you can also create a separate class library project, put all the model classes in that class library project, and refer to that class library project in your MVC application. We will discuss this as we progress in this course.

When you create a new ASP.NET Core Web Application using the Model-View-Controller Template, then by default, all the model classes are created inside the Models folder. And we are also going to follow this naming convention. Let us see how to create and work with models in ASP.NET Core MVC Application.

Adding Models Folder in ASP.NET Core Application:

Right-click on your project, then select add => new folder option from the context menu to add a new folder. Then, rename the folder name as Models. Here, we want to create a model for displaying student data. So, create a class file named Student.cs within the Models folder. Once you create the Student model, then the folder structure of your application should look as shown below.

Adding Models Folder in ASP.NET Core Application

Now open the Student.cs class file and then copy and paste the following code. As you can see, this is a very simple class having only 5 properties to hold the students’ information.

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; }
    }
}

This is our student model, which will store the student data in memory. As we already discussed, the ASP.NET Core MVC Application model also contains business logic to manage the data. So, in our example, to manage the student data, i.e., to perform the CRUD operation on the student data, we will use the following IStudentRepository interface.

Creating IStudentRepository interface:

Right-click on the Models folder and then add an interface named IStudentRepository.cs. Once you create the interface, copy and paste the following code.

namespace FirstCoreMVCWebApplication.Models
{
    public interface IStudentRepository
    {
        Student GetStudentById(int StudentId);
    }
}

As you can see, we created the above interface with one method, i.e., the GetStudentById() method, which will retrieve the student details by the student ID.

Creating StudentRepository class:

Let us create an implementation class for the above IStudentRepository interface. In our upcoming article, we will discuss retrieving student details from a database. But for this demo, let’s hardcode the student details. So, create a class file with the name StudentRepository.cs within the Models folder and then copy and paste the following code into it.

using System.Collections.Generic;
using System.Linq;

namespace FirstCoreMVCWebApplication.Models
{
    public class StudentRepository : IStudentRepository
    {
        public List<Student> DataSource()
        {
            return new List<Student>()
            {
                new Student() { StudentId = 101, Name = "James", Branch = "CSE", Section = "A", Gender = "Male" },
                new Student() { StudentId = 102, Name = "Smith", Branch = "ETC", Section = "B", Gender = "Male" },
                new Student() { StudentId = 103, Name = "David", Branch = "CSE", Section = "A", Gender = "Male" },
                new Student() { StudentId = 104, Name = "Sara", Branch = "CSE", Section = "A", Gender = "Female" },
                new Student() { StudentId = 105, Name = "Pam", Branch = "ETC", Section = "B", Gender = "Female" }
            };
        }

        public Student GetStudentById(int StudentId)
        {
            return DataSource().FirstOrDefault(e => e.StudentId == StudentId) ?? new Student();
        }
    }
}
Modify StudentController:

We already created a Controller with the name StudentController within the Controllers Folders. If you have not created it yet, add a class file with the StudentController within the Controllers folder. Then, modify the StudentController as shown below to use the StudentRepository to retrieve the student details. The Student and StudentRepository are in a separate namespace, so you must also include the namespaces.

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

namespace FirstCoreMVCWebApplication.Controllers
{
    public class StudentController : Controller
    {
        public JsonResult GetStudentDetails(int Id)
        {
            StudentRepository repository = new StudentRepository();
            Student studentDetails = repository.GetStudentById(Id);
            return Json(studentDetails);
        }
    }
}

If you are directly coming to this article without reading our previous article, please modify the Main method of the Program class as shown below, where we register the MVC service and MVC Middleware to the application request processing pipeline.

namespace FirstCoreMVCWebApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add MVC services to the container.
            builder.Services.AddMvc();

            var app = builder.Build();

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                //Configuring the MVC middleware to the request processing pipeline
                endpoints.MapDefaultControllerRoute();
            });

            app.Run();
        }
    }
}

Now run the application and navigate to https://localhost:<Port Numbet>/Student/GetStudentDetails/102 URL, and you will see the student data in JSON format, as expected in the browser, as shown in the image below.

ASP.NET Core MVC Models with Examples

How we implemented the GetStudentDetails method of Student Controller is not loosely coupled. That means tomorrow, if the implementation class of the IStudentRepository is changed, we need to change the code in the Student Controller class, as both are tightly coupled. We can overcome this problem by implementing the dependency injection design pattern that we will discuss in our upcoming article.

Role and Definition of Model in MVC Design Pattern:
  • Data Representation: Models in ASP.NET Core MVC represent the application’s data and the business logic to manage that data. They are typically Plain Old CLR Objects (POCOs) and are used to transfer data between the database and the controller and ultimately to the view.
  • Business Logic: Models often contain or are associated with the business logic needed to process data. This can include data validation, calculations, and database interaction logic.
  • Separation of Concerns: In MVC, models are part of the separation of concerns principle. They are separate from Views (user interface) and Controllers (handling user input), which allows for more modular, testable, and maintainable code.
Design Principles
  • POCO (Plain Old CLR Object): Models should be simple classes with properties that represent the data fields. They should not contain business logic or database operations directly.
  • Validation: Models can include validation logic using data annotations or by implementing validation interfaces. This helps in automatically validating data when it is being bound to a model.
  • Data Transfer Objects (DTOs): For complex scenarios, Data Transfer Objects can be used to shape the data that is sent to the View or received from the client rather than sending database entities directly.
Best Practices
  • Single Responsibility Principle: Each model should have a single responsibility and thus represent only one concept.
  • Avoid Fat Models: Business logic can be kept separate from models in service classes or business logic layers.
  • Data Encapsulation: Use properties (getters and setters) to encapsulate data and maintain control over how it is accessed and modified.

In the next article, we will discuss Views in ASP.NET Core MVC Applications with Examples. In this article, I try to explain ASP.NET Core MVC Models with Examples. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, questions, or comments about this ASP.NET Core MVC Models article.

4 thoughts on “Models in ASP.NET Core MVC”

  1. If you are following the previous section, url will not work.
    Make GetStudentDetails as private method and call from Index action.

Leave a Reply

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