MVC For Beginners: Day 3 (MODEL)

Hello Geeks!

I am back with the next part of this series and this time it's a "MODEL". This article contains a classy explanation of MVC Model for beginners with all the goodies in it, that a MVC beginner needs to understand. So let's see what I have.

Quick View

Agenda

  • A Brief Introduction
  • The Model's Role
  • Working with Model
  • Mind Twisters | Model
  • Scaffolding | Model
  • Hierarchy | Model
  • Exploring Model
  • Interview Questions | Model
  • Pin Points
  • Summary

A Brief Introduction

The world "Model" has a very strong background in our development world since it covers around hundreds of various concepts. But the Model I'll be discussing in this article as an object that you can use to communicate with your database, performs various business calculations and assists in rendering a view for your application.



The Model's Role

The Model represents the real world object and provides data to the view. A Model is a business activity on which the complete scenario of the application depends on or you can work upon.

Because of a Model in MVC there is no need to define the Data Access Layer specifically. It is understood to be encapsulated by the model itself. The following is the diagrammatic representation that explains it all:



Working with a Model

ASP.NET MVC provides a number of tools and features to build application features using only the definition of the model object. Let's explore this with a simple example.

Suppose you want to create a picture gallery. ASP.NET MVC provides you friendly tools and functionalities to create a Controller and View (as discussed in previous articles) for some sort of functioning in your gallery. These features, or I better say scenarios, can be create, delete, edit and so on for each of the model objects.

All this construction work is called Scaffolding in MVC.

Scaffolding | Model

Scaffolding in ASP.NET MVC can generate the base code you need for Create, Delete, Update and Delete (CRUD) operations in MVC for you application. It is actually a template. You just need to select one template among the others and based on that template the code required for the CRUD operations will be generated for you.

The Scaffolding is smart, it knows all the following things:

  • How to name your Controller?
  • How to name your View?
  • What code needs to be in a component?
  • Where to place all these segments in the project?
  • How each component is going to behave?

(You don't need to be worry about any of these. Scaffolding will do all that for you. I'll explain Scaffolding in a separate article in detail.)

Some Common Mind Twisters

MT1: What if there was no Model?


MT2: Is Model something new?

The answer to this twister is short, "no".

There is nothing new in it. Just remember the concept of a 3-Tier Architecture for development. There used to be three layers. One of them is "Database Layer". So the Model in MVC is the same as the Database Layer in the 3-Tier architecture. The one and only difference between them is the "separation of concerns".

MT3: Why Model? or What is the use of it?

The answer to both of these twisters is the same. Actually let me present the two most important points:

  • The three words "Separation of concerns"
  • A bridge between "Model" and "View"

MT4: How does a Model work with both a Controller and a View?

The Controller handles a request from the View and updates the Model with the corresponding changes. This results in a change of the Model's current state.



(If you guys have any other mind twisters in your mind then let me know I'll update that twister here.)

Hierarchy | Model

This is a typical Model Hierarchy in MVC. I tried to keep this simple and less descriptive since the diagram says it all.
Just go through this and understand the typical Model structure and functionalities in MVC.

Functionality Oriented Hierarchy
Structure Oriented Hierarchy
 
 

Exploring Model

Let's explore the "Model".

Click on the Solution Explorer, here you will get a list containing a set of options that includes Images, Model, View, Controller, Filter and App_Data.



Just click on "Model" and further you will see a list containing the following fields:



Actually these are not just options, these items in the list will define the working functionality of your web application. Let's explore these one by one.
  • UserContext

    "UserContext" is the first element in the list. Have a look at the "UserContet" segment:
    1. namespace MVC4Beginners.Models  
    2. {  
    3.     public class UsersContext : DbContext  
    4.     {  
    5.         public UsersContext() : base("DefaultConnection")  
    6.         {  
    7.         }  
    8. … .  
    9. … .  
    10. … .  
    11. }  
  • UserProfile

    "UserProfile" is the second in the list. It generally represents default properties or attributes of the user, like UserId and UserName. These are default attributes that are created by "Scaffolding" for you, but there is no need to worry if you want to add your attributes.
    You are always welcome to do that.
    Have a look at the "UserProfile" segment:
    1. namespace MVC4Beginners.Models  
    2. {  
    3.     public class UsersContext : DbContext  
    4.     {  
    5.         public UsersContext() : base("DefaultConnection")  
    6.         {  
    7.         }  
    8.   
    9.         public DbSet<UserProfileUserProfiles getset; }  
    10.     }  
    11.   
    12.     [Table("UserProfile")]  
    13.     public class UserProfile  
    14.     {  
    15.         [Key]  
    16.         [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]  
    17.         public int UserId getset; }  
    18.         public string UserName getset; }  
    19.     }  
    20. ….  
    21. ….  
    22. ….  
    23. }  
  • RegisterExternalLoginModel

    "RegisterExternalLoginModel" is third in the row. I don't think it sounds new to you guys if you have enough hands-on experience with HTML. It is somehow similar to that, creating a form for External login for the user.
    You can call it Registration Block or Login Block or anything you wish to. This segment also has the restricted rule "Required", in other words one cannot simply avoid it (As trick use the "*" symbol in you HTML form, while drawing the required fields).
    Have a look at "RegisterExternalLoginModel" segment:
    1. namespace MVC4Beginners.Models  
    2. {  
    3.     public class UsersContext : DbContext  
    4.     {  
    5.         … .  
    6.         … .  
    7.         … .  
    8.     }  
    9.     public class RegisterExternalLoginModel  
    10.     {  
    11.         [Required]  
    12.         [Display(Name = "User name")]  
    13.         public string UserName getset; }  
    14.   
    15.         public string ExternalLoginData getset; }  
    16.     }  
    17. ….  
    18. ….  
    19. ….  
    20. }  
  • LocalPasswordModel

    "LocalPasswordModel" is fourth in the list. I hope this segment will be familiar to you guys again. Just draw a diagram of HTML form, where you guys used to create "Password" fields and further applying some set of restrictions over that using "JavaScript" or "ASP.NET controls". Like:

          - Length Validation
          - Required Field Validation
          - Password Matching Validation
          - Error Message

    Have a look at the following "LocalPasswordModel" segment:
    1. namespace MVC4Beginners.Models  
    2. {  
    3.     public class UsersContext : DbContext  
    4.     {  
    5.         … .  
    6.         … .  
    7.         … .  
    8.     }  
    9.     public class LocalPasswordModel  
    10.     {  
    11.         [Required]  
    12.         [DataType(DataType.Password)]  
    13.         [Display(Name = "Current password")]  
    14.         public string OldPassword getset; }  
    15.   
    16.         [Required]  
    17.         [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long."MinimumLength = 6)]  
    18.         [DataType(DataType.Password)]  
    19.         [Display(Name = "New password")]  
    20.         public string NewPassword getset; }  
    21.   
    22.         [DataType(DataType.Password)]  
    23.         [Display(Name = "Confirm new password")]  
    24.         [Compare("NewPassword"ErrorMessage = "The new password and confirmation password do not match.")]  
    25.         public string ConfirmPassword getset; }  
    26.     }  
    27. ….  
    28. ….  
    29. ….  
    30. }  
  • LoginModel

    "LoginModel" is fifth in the row. This segment is somehow similar to "Login/Signup". In this segment there are generally two fields to provied, "UserName or "UserId" and "Password". This section is auto-generated for you by scaffolding.
    For security purposes you can always use a "CAPTCHA" or "Some Security Question".
    Have a look at the "LoginModel" segment as in the following:
    1. namespace MVC4Beginners.Models  
    2. {  
    3.     public class UsersContext : DbContext  
    4.     {  
    5.         … .  
    6.         … .  
    7.         … .  
    8.     }  
    9.     public class LoginModel  
    10.     {  
    11.         [Required]  
    12.         [Display(Name = "User name")]  
    13.         public string UserName getset; }  
    14.   
    15.         [Required]  
    16.         [DataType(DataType.Password)]  
    17.         [Display(Name = "Password")]  
    18.         public string Password getset; }  
    19.   
    20.         [Display(Name = "Remember me?")]  
    21.         public bool RememberMe getset; }  
    22.     }  
    23. ….  
    24. ….  
    25. ….  
    26. }  
  • RegisterModel

    "RegisterModel" is sixth in the row. I don't think it also sounds new to you guys, if you have enough hands-on experience with HTML. It is somehow similar to that, creating a Registration Page for External login for the user.
    You can call it a Registration Block or SignUp Block or anything you wish to. You can always add some other attributes, depending on you choice or depending on the requirements of your application.
    Have a look at the "RegisterModel" segment:
    1. namespace MVC4Beginners.Models  
    2. {  
    3.     public class UsersContext : DbContext  
    4.     {  
    5.         … .  
    6.         … .  
    7.         … .  
    8.     }  
    9.     public class RegisterModel  
    10.     {  
    11.         [Required]  
    12.         [Display(Name = "User name")]  
    13.         public string UserName getset; }  
    14.   
    15.         [Required]  
    16.         [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long."MinimumLength = 6)]  
    17.         [DataType(DataType.Password)]  
    18.         [Display(Name = "Password")]  
    19.         public string Password getset; }  
    20.   
    21.         [DataType(DataType.Password)]  
    22.         [Display(Name = "Confirm password")]  
    23.         [Compare("Password"ErrorMessage = "The password and confirmation password do not match.")]  
    24.         public string ConfirmPassword getset; }  
    25.     }  
    26. ….  
    27. ….  
    28. ….  
    29. }  
  • ExternalLogin

    "ExternalLogin" is the last segment in Model. It generally consists of an external user login identity and other details. These attributes and properties are accessed by some defined parameters.
    Have a look at the "ExternalLogin" segment.
    1. namespace MVC4Beginners.Models  
    2. {  
    3.     public class UsersContext : DbContext  
    4.     {  
    5.         … .  
    6.         … .  
    7.         … .  
    8.     }  
    9.     public class ExternalLogin  
    10.     {  
    11.         public string Provider getset; }  
    12.         public string ProviderDisplayName getset; }  
    13.         public string ProviderUserId getset; }  
    14.     }  
    15. }  

Interview Questions Based on "Model"

So, if you guys are into MVC then try to memorize these sets of questions based on the MVC model because in a parallel world you can encounter these questions during an interview or discussion with other Geeks and colleagues.

  1. How does a Model accommodate a Controller and a View in MVC?
  2. What does a Model represent in the MVC framework?
  3. Is a Model in MVC similar to a database layer in 3-Tier Architecture?
  4. What do you understand by Scaffolding in MVC?
  5. What are the various types of Scaffold templates available in ASP.NET MVC?
  6. Where do you see separation of concerns in MVC?
  7. What is a ViewModel in MVC?
  8. Name some application templates in MVC?
  9. What is NuGet in MVC?
  10. Can we customize Scaffolding in MVC?

(These are a very few questions. If anyone has more questions then let me know and I'll update all those here. One more thing I didn't rovide answers to in order to keep this article as brief as possible. If any of you have query regarding any question, then his/her queries are warmly welcomed.)

Points

Here's a summary of this article:

  • Deal with Data Access
  • It is just the same concept as a Database Layer in 3-Tier Architecture
  • Works as an interface between Controller and View
  • Necessary (as per the separation of concerns)
  • Scaffolding, "A construction work in MVC"
  • Various types of scaffold templates

Summary

I used some complex terms in this article like Scaffolding, templates and so on. I'll explain all these terms in a separate article of this series because all these are as important as learning OOP concepts before going through any object oriented language.

A few tips from my side is that, if you guys really want to become familiar with MVC:

  • Take your time
  • Do as much practise you can (implementation)
  • Try to "learn" things.. Don't just "study" (I mean it)
  • Try to discuss things with friends, colleagues or in forums (such as C# Corner)
  • If you experience any problem, then your queries are welcome.

I hope you guys enjoyed this.

#HappyCoding


Similar Articles