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 :
- Round Trip
- Web Server
- Session
- Developer Tools
- HTTP Request
- HTTP GET / HTTP POST
Difference between Asp.Net Web Form and ASP.NET MVC
SR.NO. | AS{P.NETWebForm | ASP.NETMVC |
1 | Asp.net web form having event basis programming. | ASP.NETMVC not having server-side event basis programming. Clientside event you can work out. |
2 | ASP.NETweb form having server-side controls | AS{P.NETMVC having HTML helper. |
3 | ViewState for client side state management. | ViewState not available in Asp.net MVC. |
4 | ASP.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. |
5 | As per URL basis ASPX file compulsory on the server. | As per URL basis controller should have ActionMethod in the controller. |
6 | For 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 :
- SEO friendly very descriptive URL you can design.
- Fully customize routing solution.
- WebForm page very heavy in weight but MVC is very lightweight.
- Separation of concerns.
- Test Driven Development.
- Faster comparatively AS{P.NET WebForm
- You can design Single Page Application very efficiently.
- You can use the power of React, Angular, and other javascript frameworks very easily.
- Freedom to choose view engine as per your requirement.
- No heavy server-side controls.
- Freedom to create customized HTML helper and its functionality.
(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
- Model or Domain Model
- ViewModel
We use a model in MVC framework for followings
- To receive input/data from the user.
- Data validation terminology or restriction or validation can define in model.
- Transfer data to Table / Collection.
- 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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace MvcPractice.Models
- {
- public class MemberModel
- {
-
- public int MemberID { get; set; }
-
-
- public string MemberName { get; set;}
-
-
- public string MemberAddress { get; set; }
-
-
- public string MemberCity { get; set; }
-
-
- public int MemberPhone { get;set }
-
-
- public bool IsMarried { get; set; }
-
-
- public decimal MemberFees { get; set; }
- }
- }
Other Model Example with Related to ViewModel Example.
Example Model1
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace MvcPractice.Models
- {
- public class StudentModel
- {
- public int StudentID { get; set; }
- public string StandardID { get; set; }
- public string StudentName { get; set; }
- }
- }
Example Model2
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace MvcPractice.Models
- {
- public class SubjectModel
- {
- public int SubjectID { get; set; }
- public int SubjectName { get; set; }
- }
- }
On above models, ViewModel has been created.
Example ViewModel
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace MvcPractice.Models
- {
- public class StudentViewModel
- {
- public int StudentID { get; set; }
- public string StandardID { get; set; }
- public string StudentName { get; set; }
- public List<SubjectModel> SubjectList { get; set; }
- }
- }
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 |
index | Action Method |
In following image and code of StudentController you can see following methods,
StudentController.cs Code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MvcPractice.Controllers
- {
- public class StudentController : Controller
- {
-
- public ActionResult Index()
- {
- return View();
- }
-
-
- public ActionResult Details(int id)
- {
- return View();
- }
-
-
- public ActionResult Create()
- {
- return View();
- }
-
-
- [HttpPost]
- public ActionResult Create(FormCollection collection)
- {
- try
- {
-
-
- return RedirectToAction("Index");
- }
- catch
- {
- return View();
- }
- }
-
-
- public ActionResult Edit(int id)
- {
- return View();
- }
-
-
- [HttpPost]
- public ActionResult Edit(int id, FormCollection collection)
- {
- try
- {
-
-
- return RedirectToAction("Index");
- }
- catch
- {
- return View();
- }
- }
-
-
- public ActionResult Delete(int id)
- {
- return View();
- }
-
-
- [HttpPost]
- public ActionResult Delete(int id, FormCollection collection)
- {
- try
- {
-
-
- return RedirectToAction("Index");
- }
- catch
- {
- return View();
- }
- }
- }
- }
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
- View (WebForm / Content WebForm Page)
- Layout View (Master Page)
- 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 |
View | WebForm |
View with Layout View | WebForm Page (Content Page) with Master page attached. (.aspx page) |
View without Layout View | WebForm Page (.aspx Page) without Master page attached. |
Layout View | Master Page (.Master page) |
Partial View | User Control (.ascx page) |
View with Layout View Selection and StudentModel
- @model IEnumerable<MvcPractice.Models.StudentModel>
-
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>Index</h2>
-
- <p>
- @Html.ActionLink("Create New", "Create")
- </p>
- <table class="table">
- <tr>
- <th>
- @Html.DisplayNameFor(model => model.StudentID)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.StandardID)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.StudentName)
- </th>
- <th></th>
- </tr>
-
- @foreach (var item in Model) {
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.StudentID)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.StandardID)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.StudentName)
- </td>
- <td>
- @Html.ActionLink("Edit", "Edit", new { }) |
- @Html.ActionLink("Details", "Details", new { }) |
- @Html.ActionLink("Delete", "Delete", new { })
- </td>
- </tr>
- }
-
- </table>
View without Layout View Selection and StudentModel
- @model IEnumerable<MvcPractice.Models.StudentModel>
-
- @{
- Layout = null;
- }
-
- <!DOCTYPE html>
-
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
- </head>
- <body>
- <p>
- @Html.ActionLink("Create New", "Create")
- </p>
- <table class="table">
- <tr>
- <th>
- @Html.DisplayNameFor(model => model.StudentID)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.StandardID)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.StudentName)
- </th>
- <th></th>
- </tr>
-
- @foreach (var item in Model) {
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.StudentID)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.StandardID)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.StudentName)
- </td>
- <td>
- @Html.ActionLink("Edit", "Edit", new { }) |
- @Html.ActionLink("Details", "Details", new { }) |
- @Html.ActionLink("Delete", "Delete", new { })
- </td>
- </tr>
- }
-
- </table>
- </body>
- </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 NAME | LOCATION 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
- 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.
- ~/Content/bootstrap.css
- ~/Content/site.css
Bundle Example 2
- 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.
- ~/Scripts/bootstrap.js
- ~/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
- using System.Web;
- using System.Web.Mvc;
-
- namespace MvcPractice
- {
- public class FilterConfig
- {
- public static void RegisterGlobalFilters(GlobalFilterCollection filters)
- {
- filters.Add(new HandleErrorAttribute());
- }
- }
- }
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
-
- namespace MvcPractice
- {
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Friend", action = "Index", id = UrlParameter.Optional }
- );
- }
- }
- }
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