# MVC: Model, View, Controller

When one function reads the library's data, applies its rules and draws the page, every new screen copies all three jobs and the copies drift apart; MVC splits them into a model (the data and the rules), views (how it's shown) and a controller (what a request does), so a new screen is a new view and a rule lives in one place.

Journeyman · OOP · Software Development · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Split a page's code into a model (the data and rules), views (how it's shown) and a controller (what a request does)
- Spot the smells that point to MVC: data, rules and output mixed in one function, copied for each screen
- Say which part of MVC a piece of a framework app belongs to

## Key takeaways

- The smell: data, rules and output mixed in one function, copied for each screen, with the copies disagreeing.
- The cause: three jobs (knowing the data, showing it, handling the request) live in one place, so a change to any one touches them all.
- The fix: a model holds the data and rules, views only draw what they're handed, and a controller takes the request, asks the model and picks the view.
- Every web framework in this pass is built around it: controllers, templates and models are MVC's three parts.

**Before this:** *Meet the Library API* and *Repository: Ask for the Book, Not the Shelf*. A web page here is shown as its HTML lines; you don't need to know HTML beyond "`<li>` is one line of a list".

The checkout service is tested and wired; now the library goes on the web. The first thing the website needs is a page of books, each saying whether it's on the shelf. Then the phone app wants the same list, as plain data instead of a page. Then the board changes a rule. By the end of this lesson the page's code will have split three ways, into a pattern every web framework is built on: *Model, View, Controller*, or MVC.

## The symptom: two copies that disagree

Here are the website's and the phone app's handlers for `GET /books`: the code that runs when someone asks for the list of books. The library has two books on its shelves in this example, and *The Lighthouse Keeper* is out on loan. Last week the board made a new rule: a book on loan shows the day it's due back:

```csharp
List<string> books = new() { "The Lighthouse Keeper", "Rivers of Glass" };
Dictionary<string, string> dueDates = new() { ["The Lighthouse Keeper"] = "2026-03-16" };

Console.WriteLine("Website:");
Console.Write(BooksPage());
Console.WriteLine("Phone app:");
Console.Write(BooksData());

// GET /books for the website: reads the data, applies the rule and draws the page, all in one.
string BooksPage()
{
    string page = "";
    foreach (string title in books)
    {
        string status = dueDates.ContainsKey(title) ? "back on " + dueDates[title] : "on the shelf";
        page += $"<li>{title}: {status}</li>\n";
    }
    return page;
}

// GET /books for the phone app: a copy of the website's, made before the board's new rule.
string BooksData()
{
    string data = "";
    foreach (string title in books)
    {
        string status = dueDates.ContainsKey(title) ? "on loan" : "on the shelf";
        data += $"{{\"title\": \"{title}\", \"status\": \"{status}\"}}\n";
    }
    return data;
}
```

```text
Website:
<li>The Lighthouse Keeper: back on 2026-03-16</li>
<li>Rivers of Glass: on the shelf</li>
Phone app:
{"title": "The Lighthouse Keeper", "status": "on loan"}
{"title": "Rivers of Glass", "status": "on the shelf"}
```

```java
List<String> books = List.of("The Lighthouse Keeper", "Rivers of Glass");
Map<String, String> dueDates = Map.of("The Lighthouse Keeper", "2026-03-16");

// GET /books for the website: reads the data, applies the rule and draws the page, all in one.
String booksPage() {
    String page = "";
    for (String title : books) {
        String status = dueDates.containsKey(title) ? "back on " + dueDates.get(title) : "on the shelf";
        page += "<li>" + title + ": " + status + "</li>\n";
    }
    return page;
}

// GET /books for the phone app: a copy of the website's, made before the board's new rule.
String booksData() {
    String data = "";
    for (String title : books) {
        String status = dueDates.containsKey(title) ? "on loan" : "on the shelf";
        data += "{\"title\": \"" + title + "\", \"status\": \"" + status + "\"}\n";
    }
    return data;
}

void main() {
    IO.println("Website:");
    IO.print(booksPage());
    IO.println("Phone app:");
    IO.print(booksData());
}
```

```text
Website:
<li>The Lighthouse Keeper: back on 2026-03-16</li>
<li>Rivers of Glass: on the shelf</li>
Phone app:
{"title": "The Lighthouse Keeper", "status": "on loan"}
{"title": "Rivers of Glass", "status": "on the shelf"}
```

```python
books = ["The Lighthouse Keeper", "Rivers of Glass"]
due_dates = {"The Lighthouse Keeper": "2026-03-16"}


def books_page():
    """GET /books for the website: reads the data, applies the rule and draws the page, all in one."""
    page = ""
    for title in books:
        status = "back on " + due_dates[title] if title in due_dates else "on the shelf"
        page += f"<li>{title}: {status}</li>\n"
    return page


def books_data():
    """GET /books for the phone app: a copy of the website's, made before the board's new rule."""
    data = ""
    for title in books:
        status = "on loan" if title in due_dates else "on the shelf"
        data += f'{{"title": "{title}", "status": "{status}"}}\n'
    return data


print("Website:")
print(books_page(), end="")
print("Phone app:")
print(books_data(), end="")
```

```text
Website:
<li>The Lighthouse Keeper: back on 2026-03-16</li>
<li>Rivers of Glass: on the shelf</li>
Phone app:
{"title": "The Lighthouse Keeper", "status": "on loan"}
{"title": "Rivers of Glass", "status": "on the shelf"}
```

```javascript
const books = ["The Lighthouse Keeper", "Rivers of Glass"];
const dueDates = new Map([["The Lighthouse Keeper", "2026-03-16"]]);

// GET /books for the website: reads the data, applies the rule and draws the page, all in one.
function booksPage() {
  let page = "";
  for (const title of books) {
    const status = dueDates.has(title) ? "back on " + dueDates.get(title) : "on the shelf";
    page += `<li>${title}: ${status}</li>\n`;
  }
  return page;
}

// GET /books for the phone app: a copy of the website's, made before the board's new rule.
function booksData() {
  let data = "";
  for (const title of books) {
    const status = dueDates.has(title) ? "on loan" : "on the shelf";
    data += `{"title": "${title}", "status": "${status}"}\n`;
  }
  return data;
}

console.log("Website:");
console.log(booksPage().trimEnd());
console.log("Phone app:");
console.log(booksData().trimEnd());
```

```text
Website:
<li>The Lighthouse Keeper: back on 2026-03-16</li>
<li>Rivers of Glass: on the shelf</li>
Phone app:
{"title": "The Lighthouse Keeper", "status": "on loan"}
{"title": "Rivers of Glass", "status": "on the shelf"}
```

```typescript
const books: string[] = ["The Lighthouse Keeper", "Rivers of Glass"];
const dueDates = new Map<string, string>([["The Lighthouse Keeper", "2026-03-16"]]);

// GET /books for the website: reads the data, applies the rule and draws the page, all in one.
function booksPage(): string {
  let page = "";
  for (const title of books) {
    const status = dueDates.has(title) ? "back on " + dueDates.get(title) : "on the shelf";
    page += `<li>${title}: ${status}</li>\n`;
  }
  return page;
}

// GET /books for the phone app: a copy of the website's, made before the board's new rule.
function booksData(): string {
  let data = "";
  for (const title of books) {
    const status = dueDates.has(title) ? "on loan" : "on the shelf";
    data += `{"title": "${title}", "status": "${status}"}\n`;
  }
  return data;
}

console.log("Website:");
console.log(booksPage().trimEnd());
console.log("Phone app:");
console.log(booksData().trimEnd());
```

```text
Website:
<li>The Lighthouse Keeper: back on 2026-03-16</li>
<li>Rivers of Glass: on the shelf</li>
Phone app:
{"title": "The Lighthouse Keeper", "status": "on loan"}
{"title": "Rivers of Glass", "status": "on the shelf"}
```

The website follows the new rule and the phone app doesn't, because the rule lives in two copies and only one was updated. The kiosk is next, and it would be a third copy.

- **The symptom:** data, rules and output mixed in one function, copied for each screen, and the copies disagree.
- **The cause:** each handler does three different jobs at once: it knows the data and the rules, it draws the output, and it handles the request. A change to any one of them means finding every copy.

## What would you try?

**One function with a `format` parameter: `books(format)`, with an `if` for HTML and one for data.** The rule is in one place now, but the function grows an `if` for every screen (the kiosk, a large-print page), and the drawing code for all of them is tangled together.

**Copy more carefully, and leave a comment: "keep the two in step".** The phone app's author did copy carefully; the rule came later. Comments don't run.

**Store the finished HTML in the database.** Then the phone app gets HTML it can't use, and a rule change means rewriting stored pages.

What a good fix needs: the rule in one place, each screen's drawing in its own place, and one small piece that decides which to use for each request.

## The fix: three jobs, three places

A ballpark has three people for the same three jobs. The **official scorer** watches each play and decides what goes on the record. The **score book** is the record itself: every run and every out, and the rules for counting them. The **scoreboard** shows it to the crowd, and the radio announcer reads the same score book out loud. A new way to follow the game (a phone app) is one more reader of the same book.

![A ballpark: in the press box, the official scorer writes in an open score book on the desk; through the window, the big scoreboard shows "Home 3, Visitors 2"; beside the scorer, a radio announcer at a microphone reads from the same score book](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/a51b9b37ccea47d1897ddfa9d9ae1a98.webp)

In code, the three jobs get three homes. The **model** holds the data and the rules: the books, their loans, and "a book on loan shows its due date". A **view** only draws what it's handed: one for the website's page, one for the phone app's data. A **controller** takes the request, asks the model, and picks the view. The views are the part that changes, one per screen:

![MVC's roles: a request, GET /books, arrives at the controller, which asks the model (the books and the rules) for the books and hands them to a view. The two views, the web page and the phone app's data, sit in a dashed fence labeled "what changes: how it's shown"](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/aa065a9329b843d1b3ebf91a1f64c8ba.webp)

```csharp
Catalog catalog = new Catalog(
    new List<string> { "The Lighthouse Keeper", "Rivers of Glass" },
    new Dictionary<string, string> { ["The Lighthouse Keeper"] = "2026-03-16" });
BooksController controller = new BooksController(catalog);

Console.WriteLine("Website:");
Console.Write(controller.List("website"));
Console.WriteLine("Phone app:");
Console.Write(controller.List("phone app"));

record BookStatus(string Title, string Status);

// The model: the library's data and its rules, and nothing about how they're shown.
class Catalog
{
    private readonly List<string> books;
    private readonly Dictionary<string, string> dueDates;

    public Catalog(List<string> books, Dictionary<string, string> dueDates)
    {
        this.books = books;
        this.dueDates = dueDates;
    }

    public List<BookStatus> Shelf() =>
        books.Select(title => new BookStatus(title, dueDates.ContainsKey(title) ? "back on " + dueDates[title] : "on the shelf")).ToList();
}

// The views: each one only draws what it's handed.
interface IView { string Render(List<BookStatus> books); }

class WebPageView : IView
{
    public string Render(List<BookStatus> books) => string.Concat(books.Select(book => $"<li>{book.Title}: {book.Status}</li>\n"));
}

class PhoneDataView : IView
{
    public string Render(List<BookStatus> books) =>
        string.Concat(books.Select(book => $"{{\"title\": \"{book.Title}\", \"status\": \"{book.Status}\"}}\n"));
}

// The controller: takes the request, asks the model, picks the view.
class BooksController
{
    private readonly Catalog catalog;
    private readonly Dictionary<string, IView> views = new() { ["website"] = new WebPageView(), ["phone app"] = new PhoneDataView() };

    public BooksController(Catalog catalog) => this.catalog = catalog;

    public string List(string client) => views[client].Render(catalog.Shelf());
}
```

```text
Website:
<li>The Lighthouse Keeper: back on 2026-03-16</li>
<li>Rivers of Glass: on the shelf</li>
Phone app:
{"title": "The Lighthouse Keeper", "status": "back on 2026-03-16"}
{"title": "Rivers of Glass", "status": "on the shelf"}
```

```java
record BookStatus(String title, String status) { }

// The model: the library's data and its rules, and nothing about how they're shown.
class Catalog {
    private final List<String> books;
    private final Map<String, String> dueDates;

    Catalog(List<String> books, Map<String, String> dueDates) {
        this.books = books;
        this.dueDates = dueDates;
    }

    List<BookStatus> shelf() {
        return books.stream()
            .map(title -> new BookStatus(title, dueDates.containsKey(title) ? "back on " + dueDates.get(title) : "on the shelf"))
            .toList();
    }
}

// The views: each one only draws what it's handed.
interface View { String render(List<BookStatus> books); }

class WebPageView implements View {
    public String render(List<BookStatus> books) {
        String page = "";
        for (BookStatus book : books) { page += "<li>" + book.title() + ": " + book.status() + "</li>\n"; }
        return page;
    }
}

class PhoneDataView implements View {
    public String render(List<BookStatus> books) {
        String data = "";
        for (BookStatus book : books) { data += "{\"title\": \"" + book.title() + "\", \"status\": \"" + book.status() + "\"}\n"; }
        return data;
    }
}

// The controller: takes the request, asks the model, picks the view.
class BooksController {
    private final Catalog catalog;
    private final Map<String, View> views = Map.of("website", new WebPageView(), "phone app", new PhoneDataView());

    BooksController(Catalog catalog) { this.catalog = catalog; }

    String list(String client) { return views.get(client).render(catalog.shelf()); }
}

void main() {
    Catalog catalog = new Catalog(List.of("The Lighthouse Keeper", "Rivers of Glass"), Map.of("The Lighthouse Keeper", "2026-03-16"));
    BooksController controller = new BooksController(catalog);

    IO.println("Website:");
    IO.print(controller.list("website"));
    IO.println("Phone app:");
    IO.print(controller.list("phone app"));
}
```

```text
Website:
<li>The Lighthouse Keeper: back on 2026-03-16</li>
<li>Rivers of Glass: on the shelf</li>
Phone app:
{"title": "The Lighthouse Keeper", "status": "back on 2026-03-16"}
{"title": "Rivers of Glass", "status": "on the shelf"}
```

```python
from dataclasses import dataclass


@dataclass
class BookStatus:
    title: str
    status: str


class Catalog:
    """The model: the library's data and its rules, and nothing about how they're shown."""

    def __init__(self, books, due_dates):
        self.books = books
        self.due_dates = due_dates

    def shelf(self):
        return [BookStatus(title, "back on " + self.due_dates[title] if title in self.due_dates else "on the shelf")
                for title in self.books]


class WebPageView:
    """A view: it only draws what it's handed."""

    def render(self, books):
        return "".join(f"<li>{book.title}: {book.status}</li>\n" for book in books)


class PhoneDataView:
    def render(self, books):
        return "".join(f'{{"title": "{book.title}", "status": "{book.status}"}}\n' for book in books)


class BooksController:
    """The controller: takes the request, asks the model, picks the view."""

    def __init__(self, catalog):
        self.catalog = catalog
        self.views = {"website": WebPageView(), "phone app": PhoneDataView()}

    def list(self, client):
        return self.views[client].render(self.catalog.shelf())


catalog = Catalog(["The Lighthouse Keeper", "Rivers of Glass"], {"The Lighthouse Keeper": "2026-03-16"})
controller = BooksController(catalog)

print("Website:")
print(controller.list("website"), end="")
print("Phone app:")
print(controller.list("phone app"), end="")
```

```text
Website:
<li>The Lighthouse Keeper: back on 2026-03-16</li>
<li>Rivers of Glass: on the shelf</li>
Phone app:
{"title": "The Lighthouse Keeper", "status": "back on 2026-03-16"}
{"title": "Rivers of Glass", "status": "on the shelf"}
```

```javascript
// The model: the library's data and its rules, and nothing about how they're shown.
class Catalog {
  #books;
  #dueDates;
  constructor(books, dueDates) {
    this.#books = books;
    this.#dueDates = dueDates;
  }
  shelf() {
    return this.#books.map((title) => ({
      title,
      status: this.#dueDates.has(title) ? "back on " + this.#dueDates.get(title) : "on the shelf",
    }));
  }
}

// The views: each one only draws what it's handed.
class WebPageView {
  render(books) { return books.map((book) => `<li>${book.title}: ${book.status}</li>\n`).join(""); }
}

class PhoneDataView {
  render(books) { return books.map((book) => `{"title": "${book.title}", "status": "${book.status}"}\n`).join(""); }
}

// The controller: takes the request, asks the model, picks the view.
class BooksController {
  #catalog;
  #views = new Map([["website", new WebPageView()], ["phone app", new PhoneDataView()]]);
  constructor(catalog) { this.#catalog = catalog; }
  list(client) { return this.#views.get(client).render(this.#catalog.shelf()); }
}

const catalog = new Catalog(["The Lighthouse Keeper", "Rivers of Glass"], new Map([["The Lighthouse Keeper", "2026-03-16"]]));
const controller = new BooksController(catalog);

console.log("Website:");
console.log(controller.list("website").trimEnd());
console.log("Phone app:");
console.log(controller.list("phone app").trimEnd());
```

```text
Website:
<li>The Lighthouse Keeper: back on 2026-03-16</li>
<li>Rivers of Glass: on the shelf</li>
Phone app:
{"title": "The Lighthouse Keeper", "status": "back on 2026-03-16"}
{"title": "Rivers of Glass", "status": "on the shelf"}
```

```typescript
interface BookStatus { title: string; status: string; }

// The model: the library's data and its rules, and nothing about how they're shown.
class Catalog {
  private readonly books: string[];
  private readonly dueDates: Map<string, string>;
  constructor(books: string[], dueDates: Map<string, string>) {
    this.books = books;
    this.dueDates = dueDates;
  }
  shelf(): BookStatus[] {
    return this.books.map((title) => ({
      title,
      status: this.dueDates.has(title) ? "back on " + this.dueDates.get(title) : "on the shelf",
    }));
  }
}

// The views: each one only draws what it's handed.
interface View { render(books: BookStatus[]): string; }

class WebPageView implements View {
  render(books: BookStatus[]): string { return books.map((book) => `<li>${book.title}: ${book.status}</li>\n`).join(""); }
}

class PhoneDataView implements View {
  render(books: BookStatus[]): string { return books.map((book) => `{"title": "${book.title}", "status": "${book.status}"}\n`).join(""); }
}

// The controller: takes the request, asks the model, picks the view.
class BooksController {
  private readonly catalog: Catalog;
  private readonly views = new Map<string, View>([["website", new WebPageView()], ["phone app", new PhoneDataView()]]);
  constructor(catalog: Catalog) { this.catalog = catalog; }
  list(client: string): string { return this.views.get(client)!.render(this.catalog.shelf()); }
}

const catalog = new Catalog(["The Lighthouse Keeper", "Rivers of Glass"], new Map([["The Lighthouse Keeper", "2026-03-16"]]));
const controller = new BooksController(catalog);

console.log("Website:");
console.log(controller.list("website").trimEnd());
console.log("Phone app:");
console.log(controller.list("phone app").trimEnd());
```

```text
Website:
<li>The Lighthouse Keeper: back on 2026-03-16</li>
<li>Rivers of Glass: on the shelf</li>
Phone app:
{"title": "The Lighthouse Keeper", "status": "back on 2026-03-16"}
{"title": "Rivers of Glass", "status": "on the shelf"}
```

The phone app follows the board's rule now, and nobody fixed the phone app: the rule moved into the model, and both views draw what the model hands them. When the kiosk arrives, it's one new view and one line in the controller's list. When the board changes a rule, it changes in `Catalog`, once.

**Where the languages differ.** The views keep one promise, `render`, written as an interface in C#, Java and TypeScript; Python and JavaScript let any object with a `render` method be a view. Each page ends with a line break, so the programs print it without adding another: `Console.Write` in C#, `IO.print` in Java, `end=""` in Python, and `trimEnd()` before `console.log` in JavaScript and TypeScript.

## How it got its name

The three parts are named for their jobs: the **model** (the data and its rules), the **view** (how it's shown) and the **controller** (what a request or a click does). The pattern, **Model-View-Controller**, was first written down in 1979, for programs with windows and a mouse, and web frameworks took it up twenty years later. Keeping each job in its own place has a name of its own, too: **separation of concerns**. And look at the views: each is one way of drawing, handed to the controller and swapped by client, which is a strategy from Pass 2, and the dictionary of views is Pass 1's dictionary of functions.

## Where you've already used it

Every web framework in this pass is built around these three parts. The controller and the model are your classes; the views are usually **templates**: a page with blanks the framework fills in with the model's data. A framework can also draw plain data (JSON) for a phone app by itself, so its "data view" is often one line. These aren't run here: each needs its framework's project around it. Versions checked on 2026-11-01.

```csharp
// ASP.NET Core 10 MVC: the controller asks the model (handed in) and picks a view.
// View(...) fills in the template Views/Books/Index.cshtml; Ok(...) draws the same books as JSON.
public class BooksController(Catalog catalog) : Controller
{
    [HttpGet("/books")]
    public IActionResult Index() => View(catalog.Shelf());

    [HttpGet("/api/books")]
    public IActionResult Data() => Ok(catalog.Shelf());
}
```

```java
// Spring Boot 4.1 (Spring MVC): a @Controller returns the template's name, "books"
// (templates/books.html, filled in by Thymeleaf); a @ResponseBody method draws JSON.
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class BooksController {
    private final Catalog catalog;

    public BooksController(Catalog catalog) { this.catalog = catalog; }

    @GetMapping("/books")
    public String page(Model model) {
        model.addAttribute("books", catalog.shelf());
        return "books";
    }

    @GetMapping("/api/books")
    @ResponseBody
    public List<BookStatus> data() { return catalog.shelf(); }
}
```

```python
# FastAPI 0.162 with Jinja2 3.1 templates: the endpoint is the controller; the template
# books.html is the web page's view; returning the list draws it as JSON.
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates

from library import catalog

app = FastAPI()
templates = Jinja2Templates(directory="templates")


@app.get("/books")
def page(request: Request):
    return templates.TemplateResponse(request, "books.html", {"books": catalog.shelf()})


@app.get("/api/books")
def data():
    return catalog.shelf()
```

```javascript
// Express 5.3: the route's function is the controller; res.render fills in the
// template views/books.ejs, and res.json draws the same books as data.
import express from "express";
import { catalog } from "./library.js";

const app = express();
app.set("view engine", "ejs");

app.get("/books", (req, res) => res.render("books", { books: catalog.shelf() }));
app.get("/api/books", (req, res) => res.json(catalog.shelf()));

app.listen(3000);
```

```typescript
// NestJS 12.3: @Controller marks the controller; @Render names the template to fill in,
// and a method with no @Render returns data, drawn as JSON.
import { Controller, Get, Render } from "@nestjs/common";
import { Catalog } from "./catalog";

@Controller()
export class BooksController {
  constructor(private readonly catalog: Catalog) {}

  @Get("books")
  @Render("books")
  page() {
    return { books: this.catalog.shelf() };
  }

  @Get("api/books")
  data() {
    return this.catalog.shelf();
  }
}
```

The controller is handed its model through its constructor, as in the last chapter: MVC and dependency injection work together in every one of these.

## When not to use it

- **For one screen that will only ever be one screen,** such as a small admin page. A function that reads the data and prints it is easier to follow than three classes.
- **When the controller starts holding the rules.** A controller that works out late fees has taken the model's job; move the rule back. Controllers should be thin: take the request, ask, pick, answer.
- **When a view starts asking the database.** A template that looks loans up itself has taken the model's job too.

The cost is jumps: to see what `GET /books` shows, you look in three files. Frameworks make the jumps predictable (controllers in one folder, views in another), which is most of what they're for.

**How often you'll meet it:** every day in web apps (our estimate).

## Check yourself

2 questions to try on the lesson page.

## So what

When one function knows the data, applies the rules and draws the screen, every new screen copies all three, and the copies drift. Split the jobs: the model knows, the views draw, the controller decides. Then a new screen is a new view, and a rule changes in one place.

## Key terms

- [Model-View-Controller](https://www.ask-codey.com/glossary/model-view-controller)
- [Separation of Concerns](https://www.ask-codey.com/glossary/separation-of-concerns)
- [Strategy Pattern](https://www.ask-codey.com/glossary/strategy-pattern)

## Cheat sheets

- [MVC: Model, View, Controller](https://www.ask-codey.com/cheat-sheets/dp-mvc-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-mvc
