ASP.NET Core MVC: controllers and Razor views

Lesson 6 of 7 · ASP.NET Core

Instead of JavaScript building the page from JSON, the server can build the HTML itself – like Django templates. In ASP.NET Core this is done by MVC controllers and Razor views (.cshtml): C# code and HTML in the same file. We build a product catalogue (Katalog) and a form for adding products, in the same project.

Before you start: required prior knowledge – the JavaScript client, templates in Django (for comparison).
How to learn: work in your own project step by step and run the application after every change; do the task at the end on your own first. The code is in C# for .NET 8 or newer (recommended: the current LTS version); the file name is in the comment at the top of every example.

Turning on MVC

// Program.cs – changes: AddControllersWithViews instead of AddControllers + a default route
builder.Services.AddControllersWithViews();       // API controllers still work

var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.MapControllers();                             // API: /api/proizvodi
app.MapControllerRoute(                           // MVC: /Katalog, /Katalog/Detalji/2
    name: "default",
    pattern: "{controller=Katalog}/{action=Index}/{id?}");
app.Run();

The route {controller=Katalog}/{action=Index}/{id?} means: /Katalog/Detalji/2 calls the action Detalji (details) of the controller KatalogController with id = 2; an empty address goes to Katalog/Index. If Program.cs contains UseDefaultFiles from lesson 5, remove it or move the client to wwwroot/admin.html, so that the home page is the catalogue.

An MVC controller

// Controllers/KatalogController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Prodavnica.Data;
using Prodavnica.Models;

namespace Prodavnica.Controllers;

public class KatalogController(ProdavnicaContext db) : Controller     // Controller (with views), not ControllerBase
{
    // GET /Katalog
    public async Task<IActionResult> Index()
    {
        var products = await db.Proizvodi.OrderBy(p => p.Naziv).ToListAsync();
        return View(products);                         // Views/Katalog/Index.cshtml
    }

    // GET /Katalog/Detalji/2
    public async Task<IActionResult> Detalji(int id)
    {
        var p = await db.Proizvodi.FindAsync(id);
        if (p == null) return NotFound();
        return View(p);
    }

    // GET /Katalog/Novi – an empty form
    public IActionResult Novi() => View(new Proizvod());

    // POST /Katalog/Novi – handling the form
    [HttpPost]
    [ValidateAntiForgeryToken]                         // protection against CSRF attacks
    public async Task<IActionResult> Novi(Proizvod p)
    {
        if (!ModelState.IsValid) return View(p);       // the same form with error messages
        db.Proizvodi.Add(p);
        await db.SaveChangesAsync();
        TempData["Message"] = $"The product \"{p.Naziv}\" has been added.";
        return RedirectToAction(nameof(Index));        // POST → redirect → GET
    }
}

The pattern is the same as in Django: GET shows the form, POST handles it, and after success there is a redirect. TempData keeps a message for one following request (like messages in Django). (Novi = new, Naziv = name.)

Razor views

@* Views/_ViewImports.cshtml – applies to all views *@
@using Prodavnica.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@* Views/Shared/_Layout.cshtml – the common frame (like base.html in Django) *@
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>@ViewData["Title"] – Shop</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
</head>
<body>
  <nav class="navbar bg-dark" data-bs-theme="dark">
    <div class="container">
      <a class="navbar-brand" asp-controller="Katalog" asp-action="Index">Shop</a>
      <a class="btn btn-sm btn-success" asp-controller="Katalog" asp-action="Novi">+ New product</a>
    </div>
  </nav>
  <main class="container py-4">
    @if (TempData["Message"] is string message)
    {
      <div class="alert alert-success">@message</div>
    }
    @RenderBody()
  </main>
</body>
</html>
@* Views/_ViewStart.cshtml *@
@{ Layout = "_Layout"; }
@* Views/Katalog/Index.cshtml *@
@model List<Proizvod>
@{ ViewData["Title"] = "Catalogue"; }

<h1 class="h3">Catalogue (@Model.Count)</h1>
<div class="row g-3">
  @foreach (var p in Model)
  {
    <div class="col-12 col-sm-6 col-lg-4">
      <div class="card h-100">
        <div class="card-body">
          <h2 class="h5">@p.Naziv</h2>
          <p class="mb-1">@p.Cena din</p>
          @if (p.Kolicina == 0)
          {
            <span class="badge bg-danger">out of stock</span>
          }
          else
          {
            <span class="badge bg-success">in stock: @p.Kolicina</span>
          }
        </div>
        <div class="card-footer">
          <a asp-action="Detalji" asp-route-id="@p.Id">Details</a>
        </div>
      </div>
    </div>
  }
</div>
RazorMeaning
@model List<Proizvod>the type of data the view gets from the controller (View(products))
@p.Nazivprinting a value – automatically "escaped" (protection against XSS)
@foreach, @ifC# loops and conditions inside HTML
asp-action, asp-route-idtag helpers: they build the correct address (/Katalog/Detalji/2)
@RenderBody()the place where the view is inserted (like {% block %} in Django)

A form with validation

@* Views/Katalog/Novi.cshtml *@
@model Proizvod
@{ ViewData["Title"] = "New product"; }

<h1 class="h3">New product</h1>
<form asp-action="Novi" method="post" style="max-width: 420px">
  <div asp-validation-summary="ModelOnly" class="text-danger"></div>
  <div class="mb-3">
    <label asp-for="Naziv" class="form-label">Name</label>
    <input asp-for="Naziv" class="form-control">
    <span asp-validation-for="Naziv" class="text-danger small"></span>
  </div>
  <div class="mb-3">
    <label asp-for="Cena" class="form-label">Price</label>
    <input asp-for="Cena" class="form-control">
    <span asp-validation-for="Cena" class="text-danger small"></span>
  </div>
  <div class="mb-3">
    <label asp-for="Kolicina" class="form-label">Quantity</label>
    <input asp-for="Kolicina" class="form-control">
    <span asp-validation-for="Kolicina" class="text-danger small"></span>
  </div>
  <button class="btn btn-success">Save</button>
</form>

asp-for="Cena" builds a field with the right type (type="number"), name and value; asp-validation-for shows the message from the [Range] attribute. A form with a tag helper automatically gets a hidden token against CSRF, which [ValidateAntiForgeryToken] checks. (Here the labels have English text written in them; without text, asp-for would show the property name.)

Web API + JavaScript or MVC?

Web API + JS client (lesson 5)MVC + Razor (this lesson)
who makes the HTMLthe browser (JavaScript)the server
good forinteractive pages, mobile apps, several clientscontent sites, forms, admin pages
search engines (SEO)hardereasier – the HTML is ready immediately

Many applications combine both – like the shop now: the catalogue in MVC, and the API for a mobile app or JavaScript. There are also Razor Pages (a view and code per page, without a controller) and Blazor (interactive pages in C# instead of JavaScript).

Practice tasks

Each task has an example, a hint and a solution.

TASK 01Difficulty: easy

The Details view

Make the view Views/Katalog/Detalji.cshtml that shows the name, price, quantity and total value (price × quantity) of a product and a link back to the catalogue.

Common mistakes and tips
  • A view must be in Views/ControllerName/ActionName.cshtml (without the word "Controller"): Views/Katalog/Index.cshtml.
  • Without @addTagHelper in _ViewImports.cshtml the asp-* attributes are not processed and the links are empty.
  • An MVC controller inherits Controller, and an API controller ControllerBase.

Check your knowledge

Open the quiz

MVC and Razor

1. What does return View(products) do in an MVC controller?




2. What is the attribute asp-for="Cena" in a form for?




3. Which action does the address /Katalog/Detalji/5 lead to with the default route?