Intro to MVC

Model-View-Controller

What is MVC?

MVC stands for Model–View–Controller

It is an architectural pattern commonly used for developing web applications, which are most websites you visit that have user interfaces and interactivity. As we build larger and larger applications, we need a better way to manage them.

MVC takes a large application and divides it into three interconnected parts:

  • The Model
  • The View
  • The Controller

Why Use MVC?

Separating our application into distinct parts does a few things:

  • First, it allows us to simplify our code. Thus, we can look only in the part that matches the functionality of interest rather than searching everywhere.

  • Next, it allows us to reuse our code. Instead of writing unique code for each part, we can write more generally and reuse the code where appropriate.


When Should MVC Be Used?

Traditionally used for desktop graphical user interfaces (GUIs), the MVC architecture has become popular for designing web applications and even mobile, desktop and other clients.

Popular programming languages like Java, C#, Python, Ruby, and PHP have MVC frameworks that are used in web application development straight out of the box.


Model

The Model handles all of the data and contains the business logic.

It is the application's dynamic data structure, independent of the user interface.

For example, the classes you create for your application (with attributes and methods) belong in the model. The model represents what is being displayed. For example, if you check your email via Gmail, the content of your emails represents the model.


View

The View is how the model is shown to the user.

It is the front-end of the application where HTML, CSS, and JavaScript languages belong.

For example, the interface you’re looking at when you check Facebook, including its styling (fonts, borders, etc) represents the view. Different people checking their Facebook will see the same interface, but different content because their feeds are unique. In other words, different people will see the same view but different models.


Controller

The Controller is the link between a user and the system.

It is responsible for controlling the flow of the program, including the interactions between the models and the views. It receives user input, translates it into the appropriate messages, and passes these messages on to one or more of the views.

For example, when you want to create or delete an email in your email client, you’re sending a message to the controller. It is responsible for updating the model (creating or deleting the email), then refreshing the view (showing you what you see on the screen).


Interactions

In addition to dividing the application into three components, the Model–View–Controller design defines the interactions between them.

The Model is responsible for managing the data of the application. It receives user input from the Controller.

The View presents the Model to the user in a particular format.

The Controller responds to user input and performs interactions on the data model objects. It receives the input, optionally validates it, and then passes the input to the Model.


.NET Core MVC

ASP.NET Core MVC is a rich framework for building web apps and APIs using the Model-View-Controller design pattern.

By providing a patterns-based way to build dynamic websites, ASP.NET enables a clean separation of concerns. It gives you full control over markup, supports TDD-friendly development and uses the latest web standards.


.NET Core Features

  • Routing
  • Model binding
  • Model validation
  • Dependency injection
  • Filters
  • Web APIs
  • Testability
  • Razor view engine
  • Strongly typed views
  • Tag Helpers
  • View Components

For now, let's concentrate on only one of these features...


What is Razor?

Razor is a markup syntax for embedding server-based code into webpages.

The Razor syntax consists of Razor markup, C#, and HTML.

Files containing Razor generally have a .cshtml file extension.


Razor Syntax

Razor supports C# and uses the @ symbol to transition from HTML to C#. Razor evaluates C# expressions and renders them in the HTML output.

When an @ symbol is followed by a Razor reserved keyword, it transitions into Razor-specific markup. Otherwise, it transitions into plain C#.

We can use Razor to call methods. Most commonly you'll see Razor used to call HTML helper methods (which we'll cover in more detail later). These methods make web programming a lot more convenient.

@Html.DisplayFor(modelItem => item.Details)

You can place an @ in front of a method call and everything up until the end of the method will be Razor. This allows us to insert Razor in our HTML.

For example, the following Razor method will produce HTML that will populate the href attribute of a link:

 <a href="@Url.Action("ToggleDone", new {id = item.ItemID})">

If an @ symbol is placed in front of the curly brace, the section between the opening and closing curly brace will all be Razor. This allows us to have multiple lines of Razor. For Example:

@{
    var quote = "There's a difference between knowing the path and walking the path. -Morpheus";
}

Let's Try it out!

Let's walk through creating an ASP.NET MVC Web Application.

We're going to create a new project in Visual Studio that allows us to manipulate data in the following ways:

  • Create
  • Read
  • Update
  • Delete

In other words, its a "CRUD" application...


The Steps...

  • Create a new project in Visual Studio
  • Choose the ASP.NET Core Web Application type and name your project
  • Choose the Web Application (Model-View-Controller) template and change the authentication to Individual User Accounts
  • Click F5 to run the MVC web application in debug mode

...now let's examine some of the files and folders that ASP.NET has created for us


The Startup.cs File

Here in the Configure method you will find various configuration settings:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

For example, the code below defines the routes that map URLs to a specific controller action.

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

What is a Controller Action?

An action is just a method on the controller.

When you see a URL arrive in the form of (something)/(something)/(something), the first piece is the controller name, second piece is the action name, and the third piece is an ID parameter.

For example, our applications About page can be found at the URL:

https:// localhost:44337/Home/About

  • 'Home' is the Controller name
  • 'About' is the Controller Action
  • and in this example there is no ID parameter

wwwroot Folder

Contains css, images, js (javascript), and lib folders

  • The css folder contains the site.css file
  • The js folder contains the site.js file

Controllers Folder

  • The controllers folder holds all of the MVC controllers. Let’s look at the HomeController.cs.
  • Notice it has methods that return the view for each of the pages of our application, such as Index(), About(), and Contact().

Models Folder

  • The models folder holds all of the classes for the data or business logic of the application.

Views Folder

  • Inside the Views folder, you will find a subfolder for each of the Controllers (for example Home, Account, Manage) plus a Shared folder.

  • Let’s first look at Index.cshtml in the Home subfolder and then run the page. See what is rendered in the browser. There is body content, but also a navbar.

  • Delete everything in the Index.cshtml except for the first few lines that include:

 @{
    ViewBag.Title = "Home Page";
 }
  • Now save and run the app. Notice what’s left. Explore and try to figure out where the navbar is coming from.

  • Now, open the Shared Folder inside Views. Double-click on _Layout.cshtml
  • The Layout page is like a template. It holds all of the other information, such as the Head section, Navbar, and Footer that we want to be applied to all views.
  • Look for @RenderBody() on the Layout page.
  • RenderBody() is where the content of each of the Views, such as Index or About, is placed with respect to the Layout page.