Models in ASP.NET Core MVC

Models in ASP.NET Core MVC Application

In this article, I am going to discuss the Models in ASP.NET Core MVC Applications with Examples. Please read our previous article, where we discussed AddController() vs AddMvc() vs AddControllersWithViews() vs AddRazorPages() method in ASP.NET Core Application. We will work with the same example we created in our How to Set up MVC in ASP.NET Core article.

What is a Model in ASP.NET Core MVC?

A model is a class with .cs (for C#) as an extension having both 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 Model in an MVC application represents the state of the application and any business logic or operations it should perform. Business logic should be encapsulated in the model, along with any implementation logic for persisting the state of the application. Strongly-typed views typically use ViewModel types designed to contain the data to display on that view. The controller creates and populates these ViewModel instances from the model.

What is the Role of Models in ASP.NET Core MVC Application?

The Models in ASP.NET Core MVC Application contain a set of classes that represent 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 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, and these data are used on Views. Views are basically the HTML Pages that get rendered into the browser of the client. In the browser, we generally perform two operations. First, we display the data to the user; second, we get the data from the user. And for both these operations, models are used.

Note: 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 and put all the model classes in that class library project and refer to that class library project in your MVC application, and we will discuss this as we progress in this course.

When you create a new ASP.NET Core Web Application using 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 the student data. So, create a class file with the name Student.cs within the Models folder. Once you create the Student model, then the folder structure of your application should look as shown below.

Models in ASP.NET Core MVC 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 student 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 is going to 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 are going to use the following IStudentRepository interface.

Creating IStudentRepository interface:

Right-click on the Models folder and then add an interface with the name 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., 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 how to retrieve 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 HomeController:

We already created a Controller with the name HomeController within the Controller Folders. If you have not created it yet, add a class file with the HomeController within the Controllers folder. And then, modify the HomeController 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 HomeController : 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 add 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 http://localhost:<portnumber>/Home/GetStudentDetails/103 URL, and you will see the student data in JSON format as expected in the browser, as shown in the below image.

ASP.NET Core MVC Models with Examples

The way we implemented the GetStudentDetails method of Home 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 Home Controller class, as both are tightly coupled. We can overcome this problem by implementing the dependency injection design pattern.

In the next article, we are going to discuss Controllers 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 need. I would like to have your feedback. Please post your feedback, question, 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 *