Loading

ASP.NET Core

What is Models in ASP.NET Core MVC?. The Complete ASP.NET Core Developer Course 2023 [Videos].

The model classes represents domain-specific data and business logic in the MVC application. It represents the shape of the data as public properties and business logic as methods. In the ASP.NET MVC Application, all the Model classes must be created in the Model folder.

Models in ASP.NET Core MVC Application

In this Video, I am going to discuss the Models in ASP.NET Core MVC application with Examples. Please read our previous Video where we discussed  Application. We are going to work with the same example that we created in our  Video.

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.

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

The Models in ASP.NET Core MVC contains a set of classes that are used to represent the domain data (you can also say the business data) as well as it also contains logic to manage the domain/business data. So, in simple words, we can say that the models in ASP.NET Core MVC Application are used to manage the data i.e. the state of the application in memory.

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 application. Models are responsible for 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 and secondly, we get the data from the user. And for both these operations models are used.

Note: It is not mandatory, but it is a good programming practice to store all the model classes within the Models folder. Even though you can also create a class library project and put all the model classes in that class library project and refer that class library project in your application and we will discuss this as we progress in this course.When you create a new ASP.NET Core Application using MVC 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.
Adding Models Folder in ASP.NET Core Application:

Right-click on your project, then select add => new folder option from the context menu which will 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 looks 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.

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 model in ASP.NET Core MVC Application 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 then copy and paste the following code in it.

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 TestStudentRepository class:

Let us create an implementation class for the above IStudentRepository interface. In our upcoming Video, we will discuss how to retrieve the student details from a database. But for this demo, lets hardcoded the student details. So, create a class file with the name TestStudentRepository.cs within the Models folder and then copy and paste the following code in it.

using System.Collections.Generic;
using System.Linq;
namespace FirstCoreMVCWebApplication.Models
{
public class TestStudentRepository : 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);
}
}
}
Modify HomeController:

We already created a Controller with the name HomeController within the Controller Folders. If you have not created yet then add a class file with the HomeController within the Controllers folder. And then modify the HomeController as shown below to use the TestStudentRepository to retrieve the student details. The Student and TestStudentRepository are present in a separate namespace, so you need to include the namespaces as well.

using FirstCoreMVCWebApplication.Models;
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCWebApplication.Controllers
{
public class HomeController : Controller
{
public JsonResult GetStudentDetails(int Id)
{
TestStudentRepository repository = new TestStudentRepository();
Student studentDetails = repository.GetStudentById(Id);
return Json(studentDetails);
}
}
}

If you are directly come to this Video, without reading our previous Video, then please modify the Startup class as shown below where we register the MVC service to the built-in dependency Injection Container as well as we add MVC Middleware to the application request processing pipeline.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace FirstCoreMVCWebApplication
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
}
}

Now run the application and navigate to http://localhost:/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.

Models in ASP.NET Core MVC

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 then we need to change the code in the Home Controller class as both are tightly coupled. We can overcome this problem by implementing a dependency injection design pattern.


See All

Comments (236 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET Core / Blog

What is ASP.NET Core?

ASP.NET Core is the new version of the ASP.NET web framework mainly targeted to run on .NET Core platform.
27-jan-2022 /16 /236

ASP.NET Core / Blog

What is ASP.NET Core Framework?

ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-enabled, Internet-connected apps. With ASP.NET Core, you can: Build web apps and services, Internet of Things (IoT) apps, and mobile backends. Use your favorite development tools on Windows, macOS, and Linux.
27-jan-2022 /16 /236

ASP.NET Core / Blog

How to Setup ASP.NET Core Environment ?

ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-enabled, Internet-connected apps. With ASP.NET Core, you can: Build web apps and services, Internet of Things (IoT) apps, and mobile backends. Use your favorite development tools on Windows, macOS, and Linux.
27-jan-2022 /16 /236