• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Sunday, August 23, 2020

Model in ASP.NET Core MVC

 Admin     August 23, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     1 comment   

In this article, I am going to discuss the Model in ASP.NET Core MVC application with an example. Please read our previous article before proceeding to this article where we discussed how to set up MVC in asp.net core application. We are going to work with the same example that we started in our previous article.

What is a Model in ASP.NET Core MVC?
Model in ASP.NET Core MVC contains a set of classes that are used to represent the domain data as well as it also contains logic to manage the domain data. So in the simple word we can say that the model in MVC is used to manage the data i.e. the state of the application in memory. It is not mandatory, but it is a good programming practice to store all model classes within the Models folder.

Let us see how to create and work with models in ASP.NET Core MVC.

Adding Models folder:
Right-click on your project, then select add => new folder option which will add a new folder. Then rename the folder name as Models. Here we want to create a model for displaying the student detail. 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.
Model in ASP.NET Core MVC Application

Now open the Student.cs class file and then copy and paste the following code.
using System;
namespace FirstCoreMVCApplication.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 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 FirstCoreMVCApplication.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 article, 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 within the Models folder and then copy and paste the following code in it.
using System.Collections.Generic;
using System.Linq;
namespace FirstCoreMVCApplication.Models
{
    public class TestStudentRepository : IStudentRepository
    {
        private List<Student> _studentList;
        public TestStudentRepository()
        {
            _studentList = 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 this._studentList.FirstOrDefault(e => e.StudentId == StudentId);
        }
    }
}
Modify the HomeController as shown below to use the TestStudentRepository to retrieve the student details.
using FirstCoreMVCApplication.Models;
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public JsonResult GetStudentDetails(int Id)
        {
            TestStudentRepository repository = new TestStudentRepository();
            Student studentDetails = repository.GetStudentById(Id);
            return Json(studentDetails);
        }
    }
}
Now run the application and you will see the student data in JSON format as expected in the browser. 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 dependency injection design pattern.

In our next article, we are going to discuss how to implement the dependency injection in ASP.NET core MVC application. Here, in this article, I try to explain the Model in ASP.NET Core MVC application. 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 article.

Summary:
I hope this post will be helpful to understand the concept of Model in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

1 comment:

  1. iremAugust 22, 2023 at 9:34 AM

    pusulabet
    sex hattı
    https://izmirkizlari.com
    rulet siteleri
    rexbet
    WXT5R

    ReplyDelete
    Replies
      Reply
Add comment
Load more...

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape