Back to: ASP.NET Core Tutorials For Beginners and Professionals
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. 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. We will work with the example we created in our Controller in ASP.NET Core MVC article.
What is a Model in ASP.NET Core MVC?
In the ASP.NET Core MVC application, a model is a class with a .cs (for C#) extension that defines the Properties and behaviors of the data entities in your application. These are simple classes that represent the objects in your application. For example, a Product model might contain properties such as ID, Name, Price, and methods that define operations related to a product.
That means the Models in the ASP.NET Core MVC Application contain a set of classes representing the domain data (you can also say the business data) and logic (validation, business, and data access logic) to manage the domain/business data. The Model is the component in the MVC Design pattern used to manage the data, i.e., the state of the application in memory.
If you are working with any web application based on the MVC design pattern, then three things are common in that MVC application: 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 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 Create the Models in the MVC Application?
It is not mandatory, but creating 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, all the model classes are created inside the Models folder by default. We are also going to follow this naming convention. Let us see how to create and work with models in an 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.
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 will store the student data in memory. As we already discussed, the 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 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, the GetStudentById() method, which retrieves 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 names 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 named StudentController within the Controllers Folder. If you have not created it, add a class file named 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. This registers the MVC Services and Middlewares to the application request processing pipeline.
namespace FirstCoreMVCWebApplication { public class Program { public static void Main(string[] args) { // Create a WebApplication builder, which provides various configuration settings // and services for the web application var builder = WebApplication.CreateBuilder(args); // Add MVC services to the service container. // This includes support for controllers and views. builder.Services.AddMvc(); // Build the application using the configured builder var app = builder.Build(); // Enable routing middleware, which matches incoming HTTP requests to endpoints defined in the application app.UseRouting(); // Map the default controller route (convention: {controller=Home}/{action=Index}/{id?}) // This means if no specific route is provided, it will default to HomeController and Index action app.MapControllerRoute( name: "default", // Name of the route pattern: "{controller=Home}/{action=Index}/{id?}" // URL pattern for the route ); // Run the application, which blocks the calling thread and starts listening for incoming HTTP requests 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.
The way we implemented the GetStudentDetails method of the 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.
Use Cases of Models in MVC Design Pattern:
- Data Representation: Models represent the data in memory used by your application. They typically map to database tables or external data sources.
- Business Logic: Models may contain business rules and validation logic, ensuring data integrity and consistency.
- Communication: Models facilitate communication between different parts of the application, such as controllers, views, and data access layers.
In the next article, I 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.
run the application and navigate to the /Home/GetStudentDetails/ID URL
If you are following the previous section, url will not work.
Make GetStudentDetails as private method and call from Index action.
very nice and very details
In .Net Core 3.1, the Json() method isn’t recognized. I returned a `new JsonResult()` instead.