MVC. You have probably come across this word whenever searching through tech topics.
MVC stands for Model–View–Controller, which is a software architectural pattern. Now to define each of these concepts:
Model: The central component of the pattern. It is the application's dynamic data structure, independent of the user interface. It directly manages the data, logic and rules of the application.
View: Any representation of information such as a chart, diagram or table. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants.
Controller: Accepts input and converts it to commands for the model or view.
---- from Wikipedia
The way I like to think of these three is:
Models are the blueprints for your objects that you create. Views are what is shown to the user interacting with the application. And Controllers are what works all the functionality and logic around the application.
Enough Explanations, the best of way of learning these concepts is seeing it in action. In this blog, we will use C# & ASP.NET. I actually learned Ruby on Rails first before switching to ASP.net and the learning curve helped because MVC was actually transferable from one framework to another. If you learned Ruby on Rails first, you will see the connections with ASP.NET.
So I've been feeling some Boba Tea lately, so let's make an MVC showing different Boba Teas if you ran your own shop and wanted to create a menu for your variety of Boba Teas.
We'll be using Visual Studio 2017 and we'll choose the .NET Framework. We'll call this project BobaTeaMVC.
We'll choose the MVC selection, which will scaffold the tools necessary, because why build it from scratch when they give the tools for it already.
Alright, let the scaffolding finish and let's take a look at the Solution Explorer.
WHOA! That's a lot of folders and files. I remember when I was learning Ruby on Rails, I was overwhelmed with all the folders and what everything is, where is the start line?
Honestly, I don't even know what everything does, same with Ruby on Rails, but I know which ones I know that I would probably be working with the most.
Let's break down the importance of the folders.
Properties - I've never really looked at this, but it looks like it contains the versions for assemblies.
References - These are the extensions and NuGet packages you install for your project. Similar to package.json or node modules if you worked in Javascript React.
App_Start - These are configurations, the important one to be familiar would be the RouteConfig.cs. We will go over this later on. BundleConfig.cs helps group scripts and stylesheets. I haven't practiced with this one yet, but that's what I know it is for so far.
Content - Most of the styling for bootstrap and css probably lives here.
Controllers - HEY! We learned this one so far! We'll go over this one because we'll be creating our own controller, but Visual Studio does provide a HomeController to start us off, even to use as reference.
fonts - Self explanatory, looks like you can provide different formats of fonts.
Models - HEY! Another one! We'll create one in here too soon.
Scripts - Where Javascript files live.
Views, Home, Shared - HEY! And the last one! and there are sub-folders in here with Home & Shared. We'll go over that last.
So we shall take this one at a time. Let's MAKE A BOBA TEA MODEL!
[Model]-V-C
Right click the Models Folder -> Add -> Class
And let's call it BobaTea.cs
//BobaTea.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BobaTeaMVC.Models
{
public class BobaTea
{
public string Flavor { get; set; }
public string HotOrCold { get; set; }
public int Price { get; set; } //We'll keep it int for simplicity
}
}
And that's it! We are setting up a BobaTea model with the properties of its flavor, whether it's hot or cold, and the price.
Now to create a controller.
Model-V-[Controller]
Right click the Controllers Folder -> Add -> Controller
This will be the BobaTeasController.cs
We'll use the plural of the model + "Controller." In practice convention, I was taught pluralizing for controller and singular for model because with controllers you are working with multiple objects of models while model represents the blueprint of an object. Seeing the exception for the HomeController because you don't necessarily have multiple homes.
Here's a discussion about working with Singular and Plural naming for the controller by Richard Dingwall. Are your ASP.NET MVC URLs consistent?
Now we hit enter and the controller creates!
I like how they leave us a nice little comment with //GET: BobaTeas (Yes please!).
So before we dive into the controller let's take a quick left turn to the RoutesConfig.cs located in the App_Start folder (The one we mentioned back above).
One important section to understand is this portion:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
This is a routing for the URL on the web browser that will be calling a controller based on what is provided. The name "Default" can be customized, just be consistent about what the route is for. I usually leave it alone. url shows the order of calling the 'controller' then a certain action or method, and an id. For example, our URL would look like this "http://localhost:51167/home/index". Defaults is basically the first page that opens when launching the site, which in this case, calls the Home controller, calls the action Index but id is an optional parameter, which if putting "localhost:51167/home/index/5" this will still show just the display for "localhost:51167/home/index".
Let's quickly peek at the HomeController.cs file. We are seeing a bunch of ActionResult keywords. This is the response to the browser request, based on that URL call.
This portion of the official Windows documentation discusses more about the controller actions and action results.
ASP.NET MVC Controller Overview (C#)
Another source from Tutorialsteacher that discusses more about the controller actions and with the RouteConfig.
Action Method
Let's quickly jump back to the RouteConfig and change the defaults controller to "BobaTeas" so we are pointing at the BobaTeas controller and know that we'll be working with that one mainly.
Alright, sorry about that tangent. NOW we shall go back to the controller. I just wanted to show the RouteConfig side so you know how the controller is being interacted.
So, let's add some Boba Tea to our Menu!! We'll instantiate an empty list and create some Boba Tea objects and add it to the list.
//using BobaTeaMVC.Models; <-- Don't forget to add this because BobaTea.cs
//is out of scope from here
List<BobaTea> bobaTeas = new List<BobaTea>();
bobaTeas.Add(new BobaTea { Flavor = "Matcha", HotOrCold = "Cold", Price = 3 });
bobaTeas.Add(new BobaTea { Flavor = "Taro", HotOrCold = "Cold", Price = 4 });
bobaTeas.Add(new BobaTea { Flavor = "Mocha", HotOrCold = "Hot", Price = 3 });
//we'll be passing the List inside View();
return View(bobaTeas);
}
One thing you'll notice, if you remember back in the HomeController, there were multiple View().
ASP.net follows through a flow in the folders, references the Home Controller to the Home Views, and you notice the matching names of the method cshtml files. The View() method is what calls that matching cshtml file.
We shall create our own view for our BobaTea Index() method.
Model-[View]-Controller
Right Click on Index() -> Add View
We'll call it Index, use the List Template.
Use a layout page, click on the 2 dots, Views Folder -> Shared -> _Layout.cshtml
You can think of files from the shared folder that would be applied to every page, for instance, headers and footers, or navigation bars.
And add the BobaTea (BobaTeaMVC.Models) in Model class.
Here is what's scaffolded (this is because of using the List Template)
So, this cshtml looks weird. This is called Razor Syntax. If you are familiar with Ruby on Rails, this is similar to ERB (mixture of Ruby with HTML). In this case, it is a mixture of C# with HTML. The @ symbol is what accesses C# syntax inside until it hits "<" symbol, which Razor will automatically detect that it is now about to read HTML syntax and stops. This is why I wanted to scaffold the template for this because I would not have known to do this if I was working from scratch.
@model IEnumerable<BobaTeaMVC.Models.BobaTea>
<p> <-- HTML Tags
@Html.ActionLink("Create New", "Create")
</p> <-- HTML Tags
Let's run this now and see how this view is translated!
Hey!! We got our Boba Teas showing up! And it's organized into a neatly set up table. You can spend some time tracing through the Razor syntax View to see where the models are being referenced. Let's make a tiny change, by adding a $ sign for the price.
And that is an introduction to MVC! I hope this tutorial of walking through ASP.net helped with understanding about the concept of Model-View-Controller. This is not even scratching the surface of using ASP.net's framework with MVC. This concept is transferred when working with different frameworks. Since I came from a Ruby on Rails background first, I had an understanding of the MVC flow when I was trying to learn ASP.NET.
I have to thank Youtuber IAmTimCorey. His video on ASP.NET MVC helped me understand working with this framework a lot.
IAmTimCorey's Youtube Channel
Where to go from here?
- Explore Restful APIs and Routing
- CRUD operations with MVC
- Connecting SQL Database with MVC
Here are some resources about MVC:
Tutorial: Implement CRUD Functionality with the Entity Framework in ASP.NET MVC
Introduction to ASP.NET MVC in C#: Basics, Advanced Topics, Tips, Tricks, Best Practices, and More
Tutorial: Get started with Razor Pages in ASP.NET Core
If you are curious about Ruby on Rails since I've mentioned it here,
you can check it out here:
Top comments (0)