ASP.NET MVC Notes - Part One

Here is a complete guide for beginners to learn ASP.NET MVC. In this series, we will go through the following points.

  • Prerequisites to learn ASP.NET MVC
  • Difference between ASP.NET Web Form and Asp.Net MVC
  • Why choose AS{P.NET MVC?
  • Overview of Model
  • Overview of View
  • Overview of Controller
  • The configuration file of ASP.NET MVC

Prerequisite to learn ASP.NET MVC

Understanding of HTML - Reader/Learner should know the basic structure of HTML file and understanding of tags of HTML.

Understanding of CSS - Reader/Learn should have the basic understanding of CSS writing and properties of CSS.

Understanding of Web Terminology - Following basic activities of web terminology :

  1. Round Trip
  2. Web Server
  3. Session
  4. Developer Tools
  5. HTTP Request
  6. HTTP GET / HTTP POST

Difference between Asp.Net Web Form and ASP.NET MVC

SR.NO. AS{P.NETWebForm ASP.NETMVC
1Asp.net web form having event basis programming.ASP.NETMVC not having server-side event basis programming. Clientside event you can work out.
2ASP.NETweb form having server-side controlsAS{P.NETMVC having HTML helper.
3ViewState for client side state management.ViewState not available in Asp.net MVC.
4ASP.NETweb form application pages divided into two parts ASPX and ASPX.CS page.ASP.NETMVC application pages divided into three part Model, View, and Controllers.
5As per URL basis ASPX file compulsory on the server.As per URL basis controller should have ActionMethod in the controller.
6For a consistent look, master pages are used in web form.For a consistent look, layout view is used in MVC.

There is a lot of changes in the web form and MVC you will come to know or you will observe the changes while you start working on ASP.NET MVC. 

Why choose Asp.Net MVC?

MVC (Model View Controller) having followings features :

  1. SEO friendly very descriptive URL you can design.
  2. Fully customize routing solution.
  3. WebForm page very heavy in weight but MVC is very lightweight.
  4. Separation of concerns.
  5. Test Driven Development.
  6. Faster comparatively AS{P.NET WebForm
  7. You can design Single Page Application very efficiently.
  8. You can use the power of React, Angular, and other javascript frameworks very easily.
  9. Freedom to choose view engine as per your requirement.
  10. No heavy server-side controls.
  11. Freedom to create customized HTML helper and its functionality. 

diagram

(Image taken from https://msdn.microsoft.com/en-us/library/dd381412(v=vs.108).aspx)

Overview of Model

Model is a simple class which created as per business logic or form requirement or database table. The model having simple public properties and model class file stored in a MODEL folder of ASP.NET MVC project structure.

Basically, there are two types of models

  1. Model or Domain Model
  2. ViewModel 

We use a model in MVC framework for followings

  1. To receive input/data from the user.
  2. Data validation terminology or restriction or validation can define in model.
  3. Transfer data to Table / Collection.
  4. To display data from table/collection and return to view.

ViewModel

As its name defines itself, ViewModel is mostly used to display joined data from various tables or very complex business summary or form. In short, ViewModel is a mixture of models to display information/data. 

Difference between Model and ViewModel is that we use Model (Domain Model) for all the purposes and ViewModel only used to pick the data and handover to view.

Example Model

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace MvcPractice.Models  
  7. {  
  8.     public class MemberModel  
  9.     {  
  10.         //Properties for Member ID get and set  
  11.         public int MemberID { get; set; }  
  12.   
  13.         //Properties for Member Name get and set  
  14.         public string MemberName { get; set;}  
  15.   
  16.         //Properties for Member Full Address get and set  
  17.         public string MemberAddress { get; set; }  
  18.   
  19.         //Properties for Member City get and set  
  20.         public string MemberCity { get; set; }  
  21.   
  22.         //Properties for Member Phone get and set  
  23.         public int MemberPhone { get;set }  
  24.   
  25.         //Properties for Member Married Yes / No get and set  
  26.         public bool IsMarried { get; set; }  
  27.   
  28.         //Properties for Membership Fees get and set  
  29.         public decimal MemberFees { get; set; }  
  30.     }  
  31. }  

Other Model Example with Related to ViewModel Example.

Example Model1

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace MvcPractice.Models  
  7. {  
  8.     public class StudentModel  
  9.     {  
  10.         public int StudentID { get; set; }  
  11.         public string StandardID { get; set; }  
  12.         public string StudentName { get; set; }  
  13.     }  
  14. }  

Example Model2

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace MvcPractice.Models  
  7. {  
  8.     public class SubjectModel  
  9.     {  
  10.         public int SubjectID { get; set; }  
  11.         public int SubjectName { get; set; }  
  12.     }  
  13. }  

On above models, ViewModel has been created.

Example ViewModel

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace MvcPractice.Models  
  7. {  
  8.     public class StudentViewModel  
  9.     {  
  10.         public int StudentID { get; set; }  
  11.         public string StandardID { get; set; }  
  12.         public string StudentName { get; set; }  
  13.         public List<SubjectModel> SubjectList { get; set; }  
  14.     }  
  15. }  

In above ViewModel example, you can see that SubjectModel is used in StudentViewModel. Why that is used is to display subject list of that student.

Overview of Controller

The Controller is the heart of MVC framework. First, the request comes to or knocks to controller and controller’s action method. The controller is also a simple class but inherited from Controller class. This class is a part or member of System.Web.Mvc namespace. The Controller reads and handles query string process at the same time.

Controller functionality

URL : www.saischool.com/student/index

URL URL Description
www.saischool.com/Domain Name
student/Controller Name
indexAction Method

In following image and code of StudentController you can see following methods,

  • Index
  • Details
  • Create
code

StudentController.cs Code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace MvcPractice.Controllers  
  8. {  
  9.     public class StudentController : Controller  
  10.     {  
  11.         // GET: Student  
  12.         public ActionResult Index()  
  13.         {  
  14.             return View();  
  15.         }  
  16.   
  17.         // GET: Student/Details/5  
  18.         public ActionResult Details(int id)  
  19.         {  
  20.             return View();  
  21.         }  
  22.   
  23.         // GET: Student/Create  
  24.         public ActionResult Create()  
  25.         {  
  26.             return View();  
  27.         }  
  28.   
  29.         // POST: Student/Create  
  30.         [HttpPost]  
  31.         public ActionResult Create(FormCollection collection)  
  32.         {  
  33.             try  
  34.             {  
  35.                 // TODO: Add insert logic here  
  36.   
  37.                 return RedirectToAction("Index");  
  38.             }  
  39.             catch  
  40.             {  
  41.                 return View();  
  42.             }  
  43.         }  
  44.   
  45.         // GET: Student/Edit/5  
  46.         public ActionResult Edit(int id)  
  47.         {  
  48.             return View();  
  49.         }  
  50.   
  51.         // POST: Student/Edit/5  
  52.         [HttpPost]  
  53.         public ActionResult Edit(int id, FormCollection collection)  
  54.         {  
  55.             try  
  56.             {  
  57.                 // TODO: Add update logic here  
  58.   
  59.                 return RedirectToAction("Index");  
  60.             }  
  61.             catch  
  62.             {  
  63.                 return View();  
  64.             }  
  65.         }  
  66.   
  67.         // GET: Student/Delete/5  
  68.         public ActionResult Delete(int id)  
  69.         {  
  70.             return View();  
  71.         }  
  72.   
  73.         // POST: Student/Delete/5  
  74.         [HttpPost]  
  75.         public ActionResult Delete(int id, FormCollection collection)  
  76.         {  
  77.             try  
  78.             {  
  79.                 // TODO: Add delete logic here  
  80.   
  81.                 return RedirectToAction("Index");  
  82.             }  
  83.             catch  
  84.             {  
  85.                 return View();  
  86.             }  
  87.         }  
  88.     }  
  89. }  

Overview of View

View has full responsibility of UI (User Interface). Controller returns the view with data. In view model receive the data and process and organize the data according to UI. In mvc razor and C# used view file extension is CSHTML and razor and VB.NET used view file extension is VBHTML.

Types of Views

  1. View (WebForm / Content WebForm Page)
  2. Layout View (Master Page)
  3. Partial View (User Control)

View

This is as simple as a web page. The view can be created with the model specification or without model specification. Controller transfers the data in multi records or single record as per the attached model. In the view, we can use layout view for header and footer consistent look.

If you are migrated from ASP.NET WebForm you know the difference between normal web form (standalone webform without master page) and content page (web form page attached with master page).

Asp.Net MVC Terminology ASP.NETWebForm Terminology
ViewWebForm
View with Layout ViewWebForm Page (Content Page) with Master page attached. (.aspx page)
View without Layout ViewWebForm Page (.aspx Page) without Master page attached.
Layout ViewMaster Page (.Master page)
Partial ViewUser Control (.ascx page)

View with Layout View Selection and StudentModel

  1. @model IEnumerable<MvcPractice.Models.StudentModel>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Index</h2>  
  8.   
  9. <p>  
  10.     @Html.ActionLink("Create New""Create")  
  11. </p>  
  12. <table class="table">  
  13.     <tr>  
  14.         <th>  
  15.             @Html.DisplayNameFor(model => model.StudentID)  
  16.         </th>  
  17.         <th>  
  18.             @Html.DisplayNameFor(model => model.StandardID)  
  19.         </th>  
  20.         <th>  
  21.             @Html.DisplayNameFor(model => model.StudentName)  
  22.         </th>  
  23.         <th></th>  
  24.     </tr>  
  25.   
  26. @foreach (var item in Model) {  
  27.     <tr>  
  28.         <td>  
  29.             @Html.DisplayFor(modelItem => item.StudentID)  
  30.         </td>  
  31.         <td>  
  32.             @Html.DisplayFor(modelItem => item.StandardID)  
  33.         </td>  
  34.         <td>  
  35.             @Html.DisplayFor(modelItem => item.StudentName)  
  36.         </td>  
  37.         <td>  
  38.             @Html.ActionLink("Edit""Edit"new { /* id=item.PrimaryKey */ }) |  
  39.             @Html.ActionLink("Details""Details"new { /* id=item.PrimaryKey */ }) |  
  40.             @Html.ActionLink("Delete""Delete"new { /* id=item.PrimaryKey */ })  
  41.         </td>  
  42.     </tr>  
  43. }  
  44.   
  45. </table>  

View without Layout View Selection and StudentModel

  1. @model IEnumerable<MvcPractice.Models.StudentModel>  
  2.   
  3. @{  
  4.     Layout = null;  
  5. }  
  6.   
  7. <!DOCTYPE html>  
  8.   
  9. <html>  
  10. <head>  
  11.     <meta name="viewport" content="width=device-width" />  
  12.     <title>Index</title>  
  13. </head>  
  14. <body>  
  15.     <p>  
  16.         @Html.ActionLink("Create New""Create")  
  17.     </p>  
  18.     <table class="table">  
  19.         <tr>  
  20.             <th>  
  21.                 @Html.DisplayNameFor(model => model.StudentID)  
  22.             </th>  
  23.             <th>  
  24.                 @Html.DisplayNameFor(model => model.StandardID)  
  25.             </th>  
  26.             <th>  
  27.                 @Html.DisplayNameFor(model => model.StudentName)  
  28.             </th>  
  29.             <th></th>  
  30.         </tr>  
  31.       
  32.     @foreach (var item in Model) {  
  33.         <tr>  
  34.             <td>  
  35.                 @Html.DisplayFor(modelItem => item.StudentID)  
  36.             </td>  
  37.             <td>  
  38.                 @Html.DisplayFor(modelItem => item.StandardID)  
  39.             </td>  
  40.             <td>  
  41.                 @Html.DisplayFor(modelItem => item.StudentName)  
  42.             </td>  
  43.             <td>  
  44.                 @Html.ActionLink("Edit""Edit"new { /* id=item.PrimaryKey */ }) |  
  45.                 @Html.ActionLink("Details""Details"new { /* id=item.PrimaryKey */ }) |  
  46.                 @Html.ActionLink("Delete""Delete"new { /* id=item.PrimaryKey */ })  
  47.             </td>  
  48.         </tr>  
  49.     }  
  50.       
  51.     </table>  
  52. </body>  
  53. </html>  

Difference between View with Layout View and View without Layout View

View with layout view there is <html> <body> tag not found but in view without layout view there is <html> <body> tag found.

Layout View

This is used for creating a consistent look in application. Within layout view, our view will be rendered. Layout view is same as the Master page of AS{P.NET WebForm. In MVC while creating a view system give us an option to select or not to select layout view. You can create n number of layout view as per your application requirement. Layout view upper cover of view in MVC.

Partial View

Partial content which can be used inside view page, Partial view reusable in many places wherever, required to display same content in the application.

Following are the MSDN link to understand the concept in detail:

ASP.NETWebForm

  •  MastePage: : https://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx
  • WebForm Page : https://msdn.microsoft.com/en-us/library/ms973868.aspx
  • User Control : https://msdn.microsoft.com/en-us/library/y6wb1a0e.aspx 

For more details on ASP.NET MVC refer the following MSDN link,

https://msdn.microsoft.com/en-us/library/dd381412(v=vs.108).aspx

Configuration file of ASP.NET MVC

In ASP.NET mvc followings are the configuration files,

  • BundleConfig.cs
  • FilterConfig.cs
  • RouteConfig.cs
  • Web.config

NOTE
In Application_start method of Global.asax file you can see registration of BundleConfig, FilterConfig and RouteConfig.

CONFIGURATION FILE NAMELOCATION OF FILE IN PROJECT FOLDER
BundleConfig.cs~/App_Start  [ In (~)Root there is App_Start folder.]
FilterConfig.cs~/App_Start  [ In (~)Root there is App_Start folder.]
RouteConfig.cs~/App_Start  [ In (~)Root there is App_Start folder.]
Web.config 1. ~/Web.Config2. ~/View/Web.Config

BundleConfig.cs 

Bundling(Grouping) CSS and JS file to load in one short in the layout page. This will reduce the loading time of CSS and JS, this is the main advantage of bundling. By default, in BundleConfig.cs file you can see five (5) bundles. In bundle config.cs file there is a method called RegisterBundles that have a parameter of class BundleCollection which is part of System.Web.Optimization. In bundle collection class, we have ADD method to add the new CSS and JS bundle.

Bundle Example 1

  1. bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.css""~/Content/site.css"));  

In above example 1, you can see ~/Content/CSS bundle created for following css files.

  1. ~/Content/bootstrap.css
  2. ~/Content/site.css

Bundle Example 2

  1. bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js""~/Scripts/respond.js")); 

In above example 2, you can see ~/bundles/bootstrap bundle created for following   JS files.

  1. ~/Scripts/bootstrap.js
  2. ~/Scripts/respond.js

NOTE

You can create n numbers of bundles with no restrictions. 

FilterConfig.cs

To create and register a filter. Filter for Error and action Filter. 

FilterConfig.cs Code

  1. using System.Web;  
  2. using System.Web.Mvc;  
  3.   
  4. namespace MvcPractice  
  5. {  
  6.     public class FilterConfig  
  7.     {  
  8.         public static void RegisterGlobalFilters(GlobalFilterCollection filters)  
  9.         {  
  10.             filters.Add(new HandleErrorAttribute());  
  11.         }  
  12.     }  

RouteConfig.cs

This is the config file to set various routing patterns. Default controller and action method can be set in this file only. 

RouteConfig.cs Code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7.   
  8. namespace MvcPractice  
  9. {  
  10.     public class RouteConfig  
  11.     {  
  12.         public static void RegisterRoutes(RouteCollection routes)  
  13.         {  
  14.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  15.   
  16.             routes.MapRoute(  
  17.                 name: "Default",  
  18.                 url: "{controller}/{action}/{id}",  
  19.                 defaults: new { controller = "Friend", action = "Index", id = UrlParameter.Optional }  
  20.             );  
  21.         }  
  22.     }  
  23. }   

Web.config

To set web server settings and configurations.

Refer this link to learn more,

  • https://stackoverflow.com/questions/19949709/use-of-authconfig-bundleconfig-filterconfig-routeconfig-and-webapiconfig-in
  • https://weblogs.ASP.NET/gunnarpeipman/asp-net-mvc-3-global-action-filters
  • https://www.c-sharpcorner.com/forums/what-is-the-purpose-of-these-files-in-asp-net-mvc


Similar Articles