[ASP.NET for Beginner] - Part 1 - MVC

MVC, em-vee-cee, model-view-controller — everyone has heard of it, but if you’re just starting to learn it, how do you do it right?

This post lays out a few basic concepts and how to apply them in real code.

See the posts in this series

1. What is MVC?

MVC is a software architecture used to build quite a lot of the apps you use on the market. The MVC pattern peels the app’s 3 layers apart into 3 different components, making development easier.

MVC stands for Model-View-Controller

These 3 components have to go together, but for a beginner it is very hard to picture how they connect. Learning any one of them first is hard when you don’t understand the other two. So I suggest just picturing each component in your head, rather than immediately digging into how they connect.

1.1. Model

The Model is how you represent data in your code. Say your database has a Users table where each user has a name, age and address; then your model is

// A basic model
public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
}

1.2. View

The View plays exactly one role: rendering the UI for the user. Textboxes (a box for typing text), dropdown lists (picking a value from a list), checkboxes (a yes/no box) are the things you usually see in a View.

For example, to display 1 user on the screen, the asp.net code is

@model User
<div>
    @Model.Name
    @Model.Age
    @Model.Address
</div>

1.3. Controller

The Controller is what decides which View gets shown when the user types a URL. It is also what receives the data from the user when they fill in a form, click a button, and so on and so forth

2. A simple example

Since this example is here to help you understand the MVC pattern, you don’t have to follow along. Just keep reading

2.1. The problem

Thế giới di động needs a website that can display a list of phones and add/delete/edit some phone (ignoring all the requirements around security, sign-in and looks)

2.2. The analysis

Reading it, we immediately see we need a model for the phone and 4 views for the 4 features: list, add, delete, edit. Since all 4 views work on the phone model, we only need 1 controller

2.3. The implementation

2.3.1. The list feature

Model

public class MobilePhone
{
    // To identify which phones
    public int Id { get; set; }
 
    public string Name { get; set; }
}

Controller

public class MobilePhoneController
{
    public void List()
    {
        // Get all phones from database
        var allPhones = database.MobilePhones;
 
        // Return the View that render a list of phones
        return View(allPhones)
    }
}

View

@model List<MobilePhone>
<div>
    <table>
        <!--Table headers-->
        <th>
            <td>Id</td>
            <td>Name</td>
        </th>
        <!--Table body-->
        <tbody>
            @foreach(var phone in Model)
            {
                <tr>
                    <td>@phone.Id</td>
                    <td>@phone.Name</td>
                </tr>
            }
        </tbody>
    </table>
</div>

ASP.NET automatically understands that the MobilePhoneController class has the path /MobilePhone

When the user points at the following URL:

yourdomain/MobilePhone/List

then, by some magic, asp.net calls the List method in this controller, runs the code in it, and returns a table listing the phones for the user

2.3.2. The add feature

Reusing the old model, we only need to add code for the View and the Controller

Controller

public class MobilePhoneController
{
    public void List()
    {
        // Get all phones from database
        var allPhones = database.MobilePhones;
 
        // Return the View that render a list of phones
        return View(allPhones)
    }
 
    // Render the Add form
    public void Add()
    {
        return View();
    }
 
    // Recieved the new phone input by user
    [HttpPost]
    public void Add(MobilePhone newPhone)
    {
        var existedPhone = database.MobilePhones.Find(newPhone.Id)
 
        if(existedPhone != null)
        {
            // Phone is existed, return the Add View
            return View(newPhone);
        }
 
        // Add new data to database
        database.MobilePhones.Add(newPhone);
 
        // Save the changes
        database.SaveChanges();
    }
}

Why are there 2 Add methods? In the first method ASP.NET returns an empty form for the user to fill in values. The 2nd method takes a newPhone parameter. That method is responsible for receiving the information posted by the user. ASP.NET is smart enough to understand on its own that it is a MobilePhone object, and this is called Model Binding. We’ll look into that topic later.

View

add the file Add.cshtml

For ASP.NET Core

@model MobilePhone
 
<form asp-action="Add" asp-controller="MobilePhone">
    <label>Id</label>
    <input asp-for="Id"/>
    <label>Name</label>
    <input asp-for="Name"/>
</form>

For the older ASP.NET MVC

@model MobilePhone
 
@using(Html.BeginForm("Add","MobilePhone",Method.Post))
{
    <label>Id</label>
    @Html.TextBoxFor(x => x.Id)
    <label>Name</label>
    @Html.TextBoxFor(x => x.Name)
}

3. Creating the project yourself

From here on you’ll need to follow along step by step

ASP.NET has quite a few versions: MVC1, MVC2, MVC3, MVC4, and most recently MVC5 and MVC Core. Version 5 and below are the old way of building, running only on Windows; MVC Core and later are the new way, able to run on Linux, Windows or MacOS. If you’re learning, I’d encourage starting from MVC Core and up, since that’s what’s hot

3.1. The software you need

3.2. Let’s go

Open VSCode, press Ctrl + ` to show the Terminal, or do it as in the picture

show termial

use cd commands to point at the folder where you want to create your project

or

open in vscode

type

dotnet new mvc

Press F5 > pick .NET Core

If you get asked “Required assets to build and debug are missing from blah blah blah”, hit Yes

yes to build

So you have created your first MVC project using ASP.NET Core. You can open the HomeController class to better understand the MVC pattern I described above.

3.3. ASP.NET Convention

Above I mentioned MobilePhoneController, whose path is /MobilePhone; likewise, in the project you just created, HomeController has the path /Home. ASP.NET understands your controller on its own and gives it the matching path.

By default, the Index methods in your controller are the ones called when the URL has nothing after it. For example with the HomeController above, if you only type https://localhost:5000/Home/ then the Index method is called and the Index.cshtml View is displayed.

So you now understand the MVC pattern well enough. In the next part I’ll continue with connecting the database and what you can do with the Model to keep it standard