MVC Model


Introduction

In my previous article we had discussed about ASP.NET MVC and little about Model, View and controller. In this article we are going to explore little more about ASP.NET MVC Model.

Getting Started

Model is referes to Data Transfer Object(DTO) in ASP.NET MVC,it is a simple CLR class where Business logic and Validations are implemented. Model defines which data type sould be used to transfer data from server to client browser or vice versa. Below is example of student model.

 public class Student   
 {   
      public int ID{get; set;}   
      public int Name{get; set;}   
      public int Class{get; set;}   
      public int Section{get; set;}   
 }  
Model is used in ASP.NET MVC View to display information and it is controled by ASP.NET MVC Controller. Below example shows how Model is used in ASP.NET MVC Controller.
 public class StudentController : Controller  
 {  
      public ActionResult Index()  
      {  
          // Student Model is being used inside this action
           Student student=new Student();  
           return View(student);  
      }  
 }  
It is good pratice to write business logic(data access part, validation etc.) in Model rather than controller, controller should contains only the UI logic. For example what model should to pass a view for displaying data etc.

AS mentioned in the above of this article that Model is a symple CLR class, which can be creating using class keyword. When you are using EntityFramework with Database first approach in you MVC project, EntityFramework creates models for your project for each SQL Table.




Normally we are creating another class for writing data access part and uses models in this class. But it is good pratic that creat a partial class for your model and write data access part and business logic in this class.
  public class Student  
   {  
     public int ID { get; set; }  
     public int Name { get; set; }  
     public int Class { get; set; }  
     public int Section { get; set; }  
     public void Save()  
     {  
       using (DataContext dc = new DataContext())  
       {  
         dc.Students.Add(this);  
         dc.SaveChanges();  
       }  
     }  
   }  

Summary

We discussed about ASP.NET MVC Model in this article, hope this article may helpful to you.

Thanks
Kailash Chandra Behera