LESSON 2 OF 20

2. MVC Architecture, Project Structure, and Building the First Page

In this lesson, you will examine Model, View, and Controller responsibilities in ASP.NET Core MVC and build a strongly typed content-listing page with routing and action methods.

45 dk 32

Introduction

In the first lesson, we planned a real-world project and prepared the ASP.NET Core MVC development environment. In this lesson, we will build the first working part of the application. Our goal is to create a page that lists content using in-memory sample data. In later lessons, the same flow will be connected to a database.

Throughout the course, we will build a small content management system. The application will list articles or news items, display detail pages, and eventually use Entity Framework Core with SQL Server for data access. The code in this lesson provides a small but dependable foundation for those future features.

ASP.NET Core MVC separates an application into three main responsibility areas: Model, View, and Controller. This separation keeps user interface code, application data, and request-handling logic independent, making the application easier to develop, test, and maintain.

We will not use a database in this lesson. However, the model and controller structure we create will remain useful when real data access is added later.

Responsibilities of the MVC components

Model

The Model represents the data used by the application and the rules associated with that data. In a content-listing scenario, a model may contain a title, summary, publication date, and author. A model should not generate HTML or know how a particular page presents its data.

In this lesson, we will use a view model instead of a database entity. A view model is designed to carry the data required by a specific screen. If a listing page needs only a title, summary, and publication date, a dedicated ArticleViewModel can expose those fields without coupling the view to a future database design.

View

The View generates the HTML sent to the user. In ASP.NET Core MVC, views are .cshtml files that use Razor syntax. C# can be embedded in a view, but the primary responsibility of a view is presentation, not data access or complex business processing.

A strongly typed view identifies the model type it expects with the @model directive. Strong typing helps detect incorrect property names during compilation and provides IntelliSense support in the development environment.

Controller

The Controller coordinates the HTTP request and the rest of the application. It receives a routed request, executes the appropriate action method, prepares the required data, and returns a View or another HTTP result.

A controller should not become a place for database queries, complex business rules, and HTML generation all at once. In this lesson, sample data will be created in the controller. In later lessons, that responsibility will move to services and Entity Framework Core.

Understanding the project structure

ASP.NET Core MVC projects use conventions for folder and file names. The basic structure at the end of this lesson will look similar to the following:

ContentPortal/
├── Controllers/
│   └── ArticlesController.cs
├── Models/
│   └── ArticleViewModel.cs
├── Views/
│   ├── Articles/
│   │   └── Index.cshtml
│   └── Shared/
│       └── _Layout.cshtml
├── wwwroot/
├── appsettings.json
└── Program.cs

The Controllers folder contains controller classes that handle requests. The Models folder contains data models or view models, while the Views folder contains Razor files. If a controller is named ArticlesController, MVC conventionally looks for its views in Views/Articles.

Program.cs registers application services and configures the HTTP request pipeline. MVC support and the default route are configured there. The wwwroot folder is reserved for CSS, JavaScript, and other static files.

Creating the model

Create a file named ArticleViewModel.cs in the Models folder:

namespace ContentPortal.Models;

public class ArticleViewModel
{
    public int Id { get; set; }

    public string Title { get; set; } = string.Empty;

    public string Summary { get; set; } = string.Empty;

    public DateTime PublishedAt { get; set; }

    public string AuthorName { get; set; } = string.Empty;
}

The Id property identifies the content item. Title and Summary are displayed on the listing page. PublishedAt represents the publication date, and AuthorName identifies the person who created the content.

Using string.Empty makes it explicit that these properties are initialized and are not expected to be null when nullable reference types are enabled. In a production application, we will add validation rules for fields such as the title and summary. For now, the model exists to demonstrate data flow and render the first page.

Creating the controller and action methods

Create ArticlesController.cs in the Controllers folder:

using ContentPortal.Models;
using Microsoft.AspNetCore.Mvc;

namespace ContentPortal.Controllers;

public class ArticlesController : Controller
{
    public IActionResult Index()
    {
        var articles = new List<ArticleViewModel>
        {
            new ArticleViewModel
            {
                Id = 1,
                Title = "Getting Started with ASP.NET Core MVC",
                Summary = "Learn the MVC components and request flow through a practical example.",
                PublishedAt = new DateTime(2024, 1, 15),
                AuthorName = "Ayse Demir"
            },
            new ArticleViewModel
            {
                Id = 2,
                Title = "Understanding Razor Views",
                Summary = "Learn how Razor syntax transforms data into HTML output.",
                PublishedAt = new DateTime(2024, 1, 20),
                AuthorName = "Mehmet Kaya"
            }
        };

        return View(articles);
    }

    public IActionResult Details(int id)
    {
        var article = new ArticleViewModel
        {
            Id = id,
            Title = "Sample article details",
            Summary = "This page demonstrates how a route parameter reaches an action method.",
            PublishedAt = DateTime.Today,
            AuthorName = "Content Team"
        };

        return View(article);
    }
}

The ArticlesController class inherits from Controller. Public methods can be treated as actions unless explicitly excluded. The Index action prepares a list and passes it to the view through View(articles).

The id parameter in the Details action receives a route value from the URL. For now, the action returns a sample object for every ID. Once database access is introduced, a missing record should normally result in NotFound().

Understanding routing

Assume that a user opens /Articles/Index in a browser. A typical conventional route is:

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

The first segment represents the controller name, the second represents the action name, and the third optional segment represents an ID. Therefore, /Articles/Index is mapped to the Index method of ArticlesController. With /Articles/Details/2, the id parameter receives the value 2.

When you create a new MVC project, verify that Program.cs contains MVC service registration and route mapping:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

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

app.Run();

AddControllersWithViews registers MVC controller and view services. MapControllerRoute defines how controller-based requests are mapped to action methods.

Creating the view

Create the Views/Articles folder and add an Index.cshtml file:

@model IEnumerable<ContentPortal.Models.ArticleViewModel>

@{
    ViewData["Title"] = "Articles";
}

<h2>Articles</h2>
<p>The sample content items in the application are listed below.</p>

<ul>
@foreach (var article in Model)
{
    <li>
        <h3>@article.Title</h3>
        <p>@article.Summary</p>
        <p>
            Author: @article.AuthorName |
            Date: @article.PublishedAt.ToString("dd.MM.yyyy")
        </p>
        <a asp-controller="Articles"
           asp-action="Details"
           asp-route-id="@article.Id">View details</a>
    </li>
}
</ul>

The first line declares that the view expects a collection of article view models. Razor uses the @foreach loop to transform each object into HTML. Expressions such as @article.Title are evaluated on the server.

The asp-controller, asp-action, and asp-route-id attributes are processed by the Anchor Tag Helper. Instead of manually concatenating URLs, the application generates links according to the route configuration. If the route changes, link-generation code is less likely to become inconsistent.

Run the application and open /Articles/Index. Because of the default route, /Articles will also commonly reach the Index action. Click a details link and observe that a URL such as /Articles/Details/1 is generated.

Adding the Details view

To make the listing links work, create Views/Articles/Details.cshtml:

@model ContentPortal.Models.ArticleViewModel

@{
    ViewData["Title"] = Model.Title;
}

<h2>@Model.Title</h2>
<p>@Model.Summary</p>
<p>Author: @Model.AuthorName</p>
<p>Published: @Model.PublishedAt.ToString("dd.MM.yyyy")</p>

<a asp-controller="Articles" asp-action="Index">Back to list</a>

When MVC sees return View(article), it looks for a view named after the action: Details.cshtml. The conventional folder is derived from the controller name, so the expected location is Views/Articles. A misspelled file or folder usually results in a view-not-found error.

Following the request flow

  1. The user opens /Articles/Index in the browser.

  2. The routing system examines the URL and selects ArticlesController.Index.

  3. The controller prepares the article list. In this example, the list is created in memory.

  4. The controller passes the list to the Razor view through View(articles).

  5. Razor converts the items into HTML and the completed response is sent to the browser.

  6. When the user clicks a details link, the route ID is bound to the Details(int id) parameter.

The controller does not write the page's HTML, the view does not query the database, and the model does not manage browser URLs. Keeping these responsibilities separate is one of the main benefits of MVC.

Common mistakes

  • Using the wrong controller name: Naming the class ArticleController instead of ArticlesController changes the route and expected view folder.
  • Placing a view in the wrong folder: Index.cshtml should be under Views/Articles.
  • Using an incompatible model type: If the controller sends a list but the view expects a single ArticleViewModel, a runtime model-type error occurs.
  • Omitting the route value: If the Details action requires an ID but the link does not provide asp-route-id, the action may receive an unexpected value.
  • Making the controller too large: Plan to move sample-data creation into a service later. The controller should coordinate the request.
  • Putting business rules in the Razor view: Prepare complex calculations in a service or controller instead of embedding them in presentation code.

Short practice exercise

Extend the example with the following exercise:

  1. Add a property named CategoryName.

  2. Assign a category to each sample article.

  3. Display the category below the title in the listing view.

  4. Add a Home/Index link next to the “Back to list” link in the details view.

  5. Temporarily link to a nonexistent action, inspect the resulting error, and then correct the link.

You can also update the Details action to return NotFound() when the ID is zero or negative. This provides an early opportunity to understand why route values should be validated before they are used.

Conclusion

In this lesson, we applied the core ASP.NET Core MVC workflow to a practical content-listing scenario. We used a model to represent data, controller actions to handle requests, and Razor views to generate HTML. We also examined conventional routing, route parameters, and Anchor Tag Helper link generation.

The content is currently stored in memory. In the next lessons, we will work with Razor layouts and reusable interface components. Later, this example list will be connected to real database data through Entity Framework Core and SQL Server. For that reason, applying naming conventions, maintaining model-view compatibility, and keeping controller responsibilities focused are important from the beginning.

Sources