Introducing MVC with ASP.NET
Tags: codenewbie, csharp, mvc, aspnet
Published: 2019-10-08 16:20:27

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](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)

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. 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/jlbii2vltcfy4y2q2bi8.png)

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.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/m0dahh288uus0bx1nkux.png)

Alright, let the scaffolding finish and let's take a look at the Solution Explorer.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/6c1h30sv2l00txl5z97e.png)

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/cjzgwux9bes214la7pdy.png)

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

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/8tc8ipvevkxn4uvl18qs.png)

And let's call it BobaTea.cs

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/7rcu6jmgxu5tbfy4te6s.png)

```csharp
//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

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ays13z93yy16wwqk1qqi.png)

This will be the BobaTeasController.cs

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/tay5kr91lxvg8onthpky.png)

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/dtvcv8s6mdwmnfa7u1s3.png)

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?](https://richarddingwall.name/2008/08/02/are-your-aspnet-mvc-urls-consistent/)

Now we hit enter and the controller creates!

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/6y6eczypln2revc2kn9e.png)

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).

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/c2z4l7acn5ntmvi6zrv3.png)

One important section to understand is this portion:

```csharp
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.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/9pnoo64pr3fk3fnndfkd.png)

This portion of the official Windows documentation discusses more about the controller actions and action results. 

[ASP.NET MVC Controller Overview (C#)](https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/aspnet-mvc-controllers-overview-cs)

Another source from Tutorialsteacher that discusses more about the controller actions and with the RouteConfig.
[Action Method](https://www.tutorialsteacher.com/mvc/action-method-in-mvc)

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.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/x1vh191w2rba7b0ny9nw.png)

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.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/kq1dcb0kgq4um1vz01qh.png)

```csharp
//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(). 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/3x96f7257auuwcdpl7xv.png)

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. 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/8zwv6t11g93ocrl4nnvm.png)

We shall create our own view for our BobaTea Index() method. 

##Model-[View]-Controller

Right Click on Index() -> Add View

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ygxg6f5voqds5i0adjnc.png)

We'll call it Index, use the List Template.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/1vtb2k3z9k73q2yt113g.png)

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. 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/0b82lpw9ebuu8zm2mb5a.png)

And add the BobaTea (BobaTeaMVC.Models) in Model class.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/afge8lluh9nivb2qe0q2.png)

Here is what's scaffolded (this is because of using the List Template)

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/htec3ssn4tbglnc6bcfu.png)

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/73rogs3pfnexh48eq8ro.png)

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. 

```razor
@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!

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ht6yt4kgn62srcov9sls.png)

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. 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/63bnykg2sfyazs58otk4.png)

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](https://www.youtube.com/user/IAmTimCorey)

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:

[ASP.NET MVC Pattern](https://dotnet.microsoft.com/apps/aspnet/mvc)

[Tutorial: Implement CRUD Functionality with the Entity Framework in ASP.NET MVC](https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application)

[Introduction to ASP.NET MVC in C#: Basics, Advanced Topics, Tips, Tricks, Best Practices, and More](https://www.youtube.com/watch?v=phyV-OQNeRM)

[Tutorial: Get started with Razor Pages in ASP.NET Core](https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/razor-pages-start?view=aspnetcore-3.0&tabs=visual-studio)

If you are curious about Ruby on Rails since I've mentioned it here,
you can check it out here:

[Ruby on Rails](https://rubyonrails.org/)