Module 1 Understanding MVC

Module Introduction

Goal of this module

  1. What MVC is and why MVC is so popular
  2. What is the relationship between MVC and web development
  3. How MVC is implemented in ASP.NET Core

The Definition of MVC

MVC is the abbreviation for Model-View-Controller. Model-View-Controller (MVC) is a software architectural pattern for implementing graphical user interface (GUI) computer applications.

This simple, straightforward definition contains rich information.

MVC is for GUI Development

MVC based application must have GUI.

MVC is a Pattern

Three steps of data processing cycle of GUI applications

  1. The application shows data to users through the user interface - Data
  2. Users change the data and express the intentions by operating the user interface - UI
  3. The application with its logic process the data and responds to the user - Logic

Roles of data processing cycle

Role Responsibility
Data = Model Carries the information shown to or collected from the users
User Interface = View Show data, collect data, pass operations to the logic
Logic = Controller Process data, respond to user operations, choose proper user interface to show data

Restrictions to the interactions between the roles in the MVC pattern.

  1. Controller:

  2. Controller responds to the commands from user

  3. Controller manipulates models

  4. Controller picks proper views for models or picks proper models for views

  5. Controller can ask the view to show the model

    1. View:
  6. View passes user's commands/operations to the controller

  7. View may or may not know the type of its model

  8. View won't know its model instance (the actual view model) until the controller assigns one

  9. View knows how to render the model when the controller asks it to do so

  10. View won't manipulate its model directly, only the controller can manipulate models

    1. Model:
  11. Model can have business logic, such as persisting the data to a database

  12. Model will be manipulated by the controller and be rendered by a view

  13. Model won't actively interact with controller, which means the model cannot manipulate the controller

  14. Model won't actively interact with a view, which means the model cannot manipulate a view

The Benefits of Using the MVC Pattern

GUI applications are event-driven. For a GUI application, whether it is a web application, a mobile application, or a desktop application, we find that we can actually can put all its logic in the event handler methods.

For example, in a button event handler method, we can validate the text in text boxes, extract the value from the selected item in a dropdown list, examine if checkboxes are checked, and then talk to the local file system, database or web services to persist the data. We call this methodology rapid-application-development (RAD). -- what we have now

RAD is just fine for small applications, but when applications grow larger and larger, the relationships between the UI instances start getting messy. Especially when multiple developers are working on code for the same group of UIs, trying to understand the logic from other developers starts to get harder and harder. The cost of maintaining the code, resolving code conflict, and fixing bugs go up.

To avoid these problems, we can do two things:

  1. Separate the data and logic from event handlers and centralize them somewhere in order to maximize code reuse
  2. For the centralized data and logic, separate them into different roles and responsibilities

After decades of experiments and polishing the processes, the software industry found that MVC (and its variants) to always be a good and stable solution. It can efficiently eliminate the problems raised by large-scale RAD. The benefits of applying the MVC pattern in large-scale GUI projects include:

  1. Robust: developers are restricted to writing code in the correct place. They can easily understand and reuse the code from others.
  2. Testable: UI is hard to test, but the models and controller separated from the UI are easy to test with unit test cases. This makes a big improvement in the software quality and development performance.
  3. Extensible: for RAD development, the more UI elements that were added, the more complicated the net formed by the UIs. But MVC splits the functionalities of an application into small vertical pillars. Each pillar formed by a suite of controller, views, and models. To expand the feature of the application we just keep adding small pillars and cover the code by unit test cases.

Implementations of an MVC Patterns

3 MVC Variants

  1. RAD + MVC pattern: for example, Windows Forms is a plain RAD framework for Windows, when writing a Windows Forms program, instead of putting all code in the event handlers, you can create models, views, and controllers to enjoy the benefits of the MVC pattern
  2. RAD + MVC framework: to avoid reinventing the wheel, developers created many reusable MVC frameworks for those plain RAD frameworks. For example, Windows Presentation Foundation (WPF) is a plain RAD framework for Windows, and PRISM is a framework which contains base classes and implemented basic infrastructures of the MVVM pattern. When using the PRISM framework, you can easily create views, models, and view-models by deriving the base classes and don't need to build them from scratch.Another example is the Angular framework. HTML+JavaScript is the traditional web client RAD framework; it's hard to create an enterprise level web application using just pure HTML+JavaScript. Angular is an MVC framework for HTML web client development. Once you use HTML and the Angular framework together, your web application becomes an MVC application.
  3. MVC application framework: there are many MVC application frameworks, such as ASP.NET MVC, ASP.NET Core, and Spring MVC. The difference between using an MVC application framework and using a RAD + MVC framework is, once you build an application on the MVC application framework, the application is constrained to be an MVC application naturally and you have no chance to make it non-MVC.

For example, when you create a web application using ASP.NET MVC, ASP.NET Core or Spring MVC, the project scaffolding will prepare the application architecture which applies the MVC pattern for you. Your job is just to keep adding models, views, and controllers to implement the requirements from customers.

MVC and Web Development

Lession Introduction

In this lesson, let's focus on how MVC impacts web development.

The Paradigms of Web Development

There are two popular paradigms of web development, the dynamic web page and web client + web service. Both of them are deeply impacted by the MVC pattern.

Dynamic Web Page

3 generations of dynamic web page

  1. CGI(Common Gateway Interface) generation: It keeps listening to the HTTP requests that come from the users' web browser, extracts the inputs, executes the calculation and wraps the execution results in HTML tags such as <input>, <form>. Usually, CGI applications are written in pure programming languages such as C and C++.
  2. Server Page generation: The name server (generated) page is used to distinguish from the static page. Static page means the HTML pages (.html files) exist on the web server statically, before the users' request for them, and the content in the HTML pages won't change and won't be impacted by the users' requests. What makes the previously mentioned CGI development inefficient, is the business logic.
  3. MVC based web application: Since server pages are an event-driven RAD technology, it inherits the flaws of event-driven development - most of the code is written in event handlers. It's easy to grow the web application quickly but hard to maintain well. So developers transformed the web application framework using the MVC pattern. The server pages become views. Logic and data are encapsulated into controllers and models. Thus the MVC based web application is neat, robust, extensible, and easy to maintain. Transformed by the MVC pattern, the new generation of ASP.NET is called ASP.NET MVC.

Web Client + Web Service

Mobile apps: the view is an iOS app page, the model is the data from the web service, the controller is an instance of a Swift/Objective-C class

SPA: the view is an HTML page, the model is a JavaScript object that holds the data from the web service, and the controller is also a JavaScript object

Desktop application: the view is an instance of a UI component (form, window, page, user control, etc.), while the model and controller are class instances

The Execution Cycle of ASP.NET Core Web Application
  1. Receive a Command: the command is an HTTP request sent by a web browser. The HTTP request can be launched by an input in the address bar, by clicking a hyperlink, or by submitting a form, etc. Each HTTP request carries the message of the user's intention and will be handled by the web server on which the ASP.NET Core application is hosted.

  2. URL Routing: each HTTP request contains a URL, and this URL indicates which application, which controller, and which action will process the command. If the URL routing doesn't find a matching destination, a 404 Not Found HTTP response will be sent back.

  3. Action Execution: once the command is routed to its destination action (a method of the controller class), the action will extract the information and data from the HTTP request and begin to process it. If needed, models will be involved in this step.

  4. View Rendering: the action in the controller triggers the view engine to render the specific view (a .cshtml file). The view engine, called Razor, will generate the final HTML content and that content will be sent back to the user's web browser through the HTTP response. The action may pass a model object to the view, if so, and based on the rendering logic, the data carried by the model object will be woven into the HTML content and shown in the user's web browser.

Lab

Scaffold the Web Application

  1. Create a folder for your project called C:\Projects\MyWebApp and open this folder in Visual Studio Code
  2. In the terminal, run the command dotnet new mvc
  3. Open the Program.cs. Wait for the prompt and generate configuration files.
  4. Delete and recreate the Models, Views, and Controllers folders
rd Models /s /q
rd Views /s /q
rd Controllers /s /q
md Models
md Views
md Controllers

Add Model

  1. Right click the Models folder, then click New File to create Product.cs file.
  2. Open the file and add the code below. The Product is a model class:
namespace MyWebApp.Models {
    public class Product {
        public int ID { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }
}

Please note, in the rest of the course, I will reference these step as Create the file ... in the folder ..., then add the code below.

Add Controller

Create the fileProductController.csin theControllersfolder, then add the code below:

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using MyWebApp.Models;

namespace MyWebApp.Controllers {
    public class ProductController : Controller {
        public IActionResult ShowAll() {
            ViewData["Heading"] = "All Products";
            var products = new List
<
Product
>
();
            products.Add(new Product { ID = 101, Name = "Apple", Price = 1.1 });
            products.Add(new Product { ID = 202, Name = "Bike", Price = 2.2 });
            products.Add(new Product { ID = 303, Name = "Calculator", Price = 3.3 });
            return View(products);
        }
    }
}

Please note:

  • In the rest of the course, we will omit the code for using namespaces.
  • The class ProductControlleris an ASP.NET Core controller
  • The name of the controller isProduct, not the class name.
  • Do NOT use plural nouns for the web application controller. That means,ProductControlleris the correct name butProductsControlleris not. We will explain this in detail in Module 03.
  • The method ShowAllis an action.

Add View

  1. Create the folderProductin theViewsfolder. This indicates we are creating views for the controller whose name isProduct
  2. Create the view fileShowAll.cshtmlin the folderProduct. This indicates we are creating the default view for theShowAllaction.
  3. The code in this file is:
@model List<MyWebApp.Models.Product>

<html>
    <body>
        <h1>@ViewData["Heading"]</h1>
        <table border="1">
            <tr>
                <td>ID</td>
                <td>Name</td>
                <td>Price</td>
            </tr>
            @foreach(var p in Model){
                <tr>
                    <td>@p.ID</td>
                    <td>@p.Name</td>
                    <td>@p.Price</td>
                </tr>
            }
        </table>
    </body>
</html>

Run the Application

Since we intentionally avoided the default URL route of ASP.NET Core, when you run the application, your web browser should have a404 Not FoundHTTP error. But if you accesshttp://localhost:5000/Product/ShowAll(case insensitive), you make the model, controller, and view work!

results matching ""

    No results matching ""