ASP.NET CORE MVC Model
In this tutorial will discuss and understand models in asp.net core mvc. what is purpose of model and how to add models in asp.net core mvc.
The Model in asp.net core MVC nothing but the class. The model does NOT depend on the controller or the view.
The Model is the representation of the data being posted to the Controller, the data being worked on in a View or the representation of the domain specific entities operating in the business tier.
The Model contains core application information. It includes data, validation rules, data access, and aggregation logic.
The Model is known as domain object or domain entity which implements domain logic. In simple terms, this logic is used to handle the data passed between the database and the user interface (UI).
Let’s now take an example to display student information like id,name,class,age and school.
We need to follow below steps while creating models.
- Identify property. Identify property required for our class and includes naming of the property
- Identify data type.: Identify data type is important to avoid future type casting when implement
- Create a model to represent: With above information we will be creating a class that represents data.
- Create class process data: We need one more class to manage student data and will be responsible for communicating with the database server.
- Pass data to the particular: We need to model to view the particular view.
Model contains a set of classes that represent data and the logic to manage that data. So, to represent the student data that we want to display, we use the following Student class.
public class Student { /// /// GTechFluent Student Information ///
public int ID { get; set; } public string Name { get; set; } public string Class { get; set; } public int Age { get; set; } public string School { get; set; } }
We have now added model to represent data and now we need one more class fetch data from database and get student information. Will create one interface and provide implementation on StudentRespository class.
interface IStudentRespository { Student GetStudent(int id); }
public class StudentRespository : IStudentRespository { private List _students; public StudentRespository() { students = new List() { new Student() { Id = 1, Name = "Johnny", Age = 15, Class = "A", School = "Gtechfluent" }, new Student() { Id = 2, Name = "Mary", Age = 20 , Class = "B", School = "Gtechfluent" }, new Student() { Id = 3, Name = "Bob", Age = 17, Class = "C", School = "Gtechfluent" }, }; } public Student GetStudent(int id) { return _students.FirstOrDefault(s => s.Id == id); } }
We will implement dependency in our next video of controller in asp.net core mvc
You can watch our video version of this tutorial with step by step explanation.