Home » Blog » .NET 6 MVC Series – Article 1

.NET 6 MVC Series – Article 1

.net 6 mvc

We will start with .NET 6 MVC series.

We will try to cover maximum MVC concepts in a series of articles.

Pre-Requisites

Any of the below IDEs/code editors will work:

Let’s also install an express edition of SQL Server to work with databases and stuff.

SQL Server Express Edition

First MVC Project

Let’s open VS 2022 and create our first MVC project.

template
create project
project-created

The project creation is a very straight forward process:

  • We choose the ASP.NET Core Web App (Model View Controller) template.
  • We provide a valid project name, location and solution name.
  • We verify the .NET 6.0 framework, uncheck the checkbox for Enable Docker (we are not going to learn Docker in this series).
  • The project is created.

Let us build and run the project to check whether the project bootstrapping is correct.

welcome-page

Folder Structure – Solution Explorer

Let us look at the underlying folder structure of the default MVC app. We have multiple files and folders.

  • Connected Services – used to add an external service, such as a WCF service
  • Dependencies – what all dependencies does the project have – frameworks, other projects, nugets
  • Properties – contains the launchSettings.json file, which in turn contains the profiles of the application. We can add multiple other profiles, such as Staging, Production etc.
  • wwwroot – contains the static files – css, js, libraries.
  • Controllers – contains the controller files – by default we have a HomeController.cs file present in it.
  • Models – contains the models, which are nothing but classes, bu default we have a ErrorViewModel.cs present in it.
  • Views – contains the views of the application – views are nothing but HTML files, by default we have 2 sub-directories : Home, Shared and _ViewImports and _ViewStart files.
  • appsettings.json – these contain the json key value pairs – such as connection strings, log file names and locations, any JWT key value pair etc.
  • Program.cs – the entry point of the application, used for services registration, middleware usage etc.

Routing

MVC apps work on the concept of routing.

Program.cs has a block of code that defines the routing used.

app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

The default pattern of routing is “controller/action/optional id parameter“.

If we do not specify the controller and action names – Home controller and Index action is picked up.

The format of a URL in MVC is – http://hostname/controller/action/optional param

Ex: https://localhost:7163/Home/Index , https://localhost:7163/Home/Privacy

Controllers

Controllers are nothing but classes, they act as a manager for the MVC app.

  • They inherit from an abstract Controller class.
  • They contain various action methods.
  • They instruct which view/model to render.

Let us create a new controller – SampleController and create few action methods in it.

new-controller
mvc-controller
sample-controller

SampleController is created with the below default code.

using Microsoft.AspNetCore.Mvc;

namespace FirstMVCProject.Controllers
{
    public class SampleController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

Let’s change the return type from View to Content as below and run the app.

    public class SampleController : Controller
    {
        public IActionResult Index()
        {
            return Content("Sample Controller - Index View");
        }
     }

Browse to https://localhost:7163/Sample/Index or https://localhost:7163/Sample, we will get the below output.

sample-index

Let’s create another action method in Sample controller.

        public IActionResult Details()
        {
            return Content("Sample Controller - Details View");
        }

Let’s browse to https://localhost:7163/Sample/Details and see the output.

sample-details

Views

Views represent the UI of the MVC app.

  • The extension is .cshtml
  • We write simple HTML in the views to create structures

Let’s create a basic table in a view and render it.

RIght click on an action method -> Add View

add view

The action method name and the view name must match.

render-table

the HTML code for a sample table is:


<div class="center">
    <table border="1" width="500px">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>City</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>John</td>
                <td>Chicago</td>
            </tr>
            <tr>
                <td>2</td>
                <td>Mary</td>
                <td>New York</td>
            </tr>
            <tr>
                <td>3</td>
                <td>Dave</td>
                <td>LA</td>
            </tr>
        </tbody>
    </table>
</div>

Let’s browse to https://localhost:7163/Sample/RenderTable

table

Models

Models are classes that define the business logic of the MVC application.

Let’s create a simple model, create an object and hydrate the view with this model.

We will create a new action method – RenderTableUsingModels and the adjoining view.

    public class PersonViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
    }
public IActionResult RenderTableUsingModels()
        {
            var persons = new List<PersonViewModel>
            {
                new PersonViewModel
                {
                    Id=1,
                    Name="John",
                    City="Chicago"
                },
                new PersonViewModel
                {
                    Id=2,
                    Name="Mary",
                    City="NY"
                },
                new PersonViewModel
                {
                    Id=3,
                    Name="Dave",
                    City="Jersey"
                },
                new PersonViewModel
                {
                    Id=4,
                    Name="Mark",
                    City="DC"
                },
            };
            return View(persons);
        }

Note that we create a list of persons and pass this to the view.

RenderTableUsingModels.cshtml:

@model IEnumerable<PersonViewModel>

<div class="center">
    <table border="1" width="500px">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>City</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>@item.Id</td>
                    <td>@item.Name</td>
                    <td>@item.City</td>
                </tr>
            }
        </tbody>
    </table>
</div>

Let’s browse to https://localhost:7163/Sample/RenderTableUsingModels

strongly typed view

This view is now strongly typed to a list of PersonViewModel.

GitHub

The complete code is available at – https://github.com/anurag1302/dotnet6-mvc

Conclusion

We have learnt about:

  • .NET 6 MVC Template – Folder Structure
  • MVC Routing
  • Models, Views, Controller

Stay tuned for the next article.

Tags:

1 thought on “.NET 6 MVC Series – Article 1”

  1. Pingback: .NET 6 MVC - Article 4 - TechnCode Tools

Leave a Reply

Your email address will not be published. Required fields are marked *