Chapter 19: Creating a website with MVC controllers
This chapter introduces MVC controllers as an alternative to Razor Pages, previews their project structure and view rendering, and frames when each approach is preferable.
After this chapter you will be able to
- Initial application choice. State the section’s initial guidance for choosing Razor Pages versus API approaches: use Razor Pages for server-side rendered applications, and use minimal APIs or web API controllers for APIs.
- Unified controller framework. Explain that ASP.NET Core merged the previously separate MVC and Web API stacks into one MVC framework, so its controllers can generate either HTML or JSON/XML responses.
- MVC project creation. Describe how to create and run an MVC web application using the ASP.NET Core Web App (Model-View-Controller) template or the dotnet new mvc command, and identify that it produces a server-rendered HTML application using controllers and Razor views.
- MVC service and endpoint setup. Explain that an MVC app registers MVC controller and Razor view services with AddControllersWithViews() and maps its controllers as endpoints with MapControllerRoute(), rather than using AddRazorPages().
- Controller actions and views. Explain that an MVC controller groups logically related action methods, that every nonabstract public controller method is an action unless marked with [NonAction], and that an action can return View() to produce a ViewResult that renders a Razor view. Describe that MVC passes data to the view as an explicit view model rather than exposing data as properties on a Razor Page PageModel.
- Conventional controller routing. Describe how MapControllerRoute uses a conventional route template with controller and action parameters, plus an optional id segment, to calculate which controller action handles a URL. Distinguish conventional routing, where one template can map to many controller endpoints, from explicit routing, where templates typically map to one endpoint.
- Controller and PageModel analogy. Explain how an MVC controller and its action methods correspond to a Razor Page PageModel and its page handlers in the MVC pattern.
- Shared request handling flow. Describe the common processing steps used by Razor Page handlers and MVC actions: dependency injection, model-bound parameters, interaction with the application model, and creation of a view model for a Razor view.
- ViewResult rendering flow. Explain how an MVC action method uses a ViewResult to render a Razor view, including the view name, optional view model, and Razor engine's generation of HTML.
- Convention-based view selection. Describe how View() without arguments selects a view by convention from the controller and action names, and how a supplied name or application-root-relative path overrides that convention.
- View model delivery. Explain how an action passes an object as a view model with View(), and how the Razor view declares the matching type with @model and accesses it through Model.
- Default Razor Pages choice. State that the book generally recommends Razor Pages rather than MVC controllers for server-rendered applications, and explain that the section helps developers decide whether to retain familiar MVC controllers or switch.
- Architectural MVC equivalence. Explain that Razor Pages and MVC controllers are architecturally essentially equivalent because both use the MVC design pattern. Distinguish this from the more visible difference of how their files are organized in a project.
- Razor Pages versus Web Forms. Distinguish Razor Pages from ASP.NET Web Forms by explaining that Razor Pages follows the MVC design pattern and exposes normal web behavior, rather than hiding the web behind a stateful desktop-style model.
- Page-focused file organization. Explain how Razor Pages co-locates a page's Razor view and nested PageModel file, while traditional MVC commonly separates controllers, views, and view models into folders organized by type.
- Razor Pages use cases. Identify content-heavy sites with mostly static display and user data-entry forms as situations where Razor Pages is especially useful, while recognizing that Razor Pages retains separation of concerns and can coexist with MVC controllers and minimal APIs in one application.
- MVC controller selection scenarios. Explain the situations in which MVC controllers are a better choice than Razor Pages: when an app does not render HTML views, when converting an existing MVC application, and when extensive partial-page updates are needed.
What it builds on
- Your first Razor Pages application (chapter 13) · Assumes familiarity with creating a Razor Pages web application.
- Views: Rendering the user interface (chapter 17) · Assumes that Razor views render a website's user interface.
- Understanding the MVC design pattern (chapter 13) · Assumes the earlier introduction to the MVC design pattern.
- Applying the MVC design pattern to Razor Pages (chapter 13) · Assumes that Razor Pages can be understood through the MVC design pattern.
- Creating Razor views (chapter 17) · Assumes familiarity with creating Razor views and passing data to them.
- Layouts, partial views, and _ViewStart (chapter 17) · Assumes familiarity with Razor view file organization and shared view features.
- What is an HTTP API, and when should you use one? (chapter 5) · The idea that an HTTP API serves mobile or client-side applications.
- Using a template to get started (chapter 3) · Using project templates to create an ASP.NET Core application.
Section by section
Introduction
This chapter introduces MVC controllers as an alternative to Razor Pages, previews their project structure and view rendering, and frames when each approach is preferable.
- MVC chapter scope: Describe the chapter's three main topics: creating an MVC application, comparing MVC controllers with Razor Pages, and returning Razor views from MVC controllers.
Why it matters: This roadmap helps you connect the chapter's comparison of application models with its practical MVC examples. - Razor Pages preference: Explain that the author generally considers Razor Pages preferable to MVC controllers for server-rendered HTML applications, while recognizing that MVC controllers are the right choice in some cases.
Why it matters: The comparison gives you a basis for choosing an application model instead of treating Razor Pages and MVC controllers as interchangeable defaults. - MVC view selection: Describe that MVC controllers can render Razor views, that the MVC framework uses conventions to locate view files, and that a controller can override those conventions by choosing a specific Razor view template.
Why it matters: Understanding both convention-based lookup and explicit view selection lets you predict or control which HTML template an MVC controller renders.
Key terms: Model-View-Controller (MVC), MVC controllers, Razor Pages, Razor views, server-rendered HTML apps, developer ergonomics, MVC framework, view files, view selection algorithm, Razor view template
19.1 Razor Pages vs. MVC in ASP.NET Core
This section positions Razor Pages, MVC controllers, and API approaches in ASP.NET Core, clarifying the terminology used for HTML and API controllers.
- Initial application choice: State the section’s initial guidance for choosing Razor Pages versus API approaches: use Razor Pages for server-side rendered applications, and use minimal APIs or web API controllers for APIs.
Why it matters: This provides a practical default for selecting an ASP.NET Core programming model before considering the later nuances. - Unified controller framework: Explain that ASP.NET Core merged the previously separate MVC and Web API stacks into one MVC framework, so its controllers can generate either HTML or JSON/XML responses.
Why it matters: This prevents you from treating MVC and web API controllers as fundamentally separate controller technologies in ASP.NET Core. - Controller terminology conventions: Describe the book’s naming convention: MVC controller commonly means a controller dedicated to HTML generation, while web API controller means a standard ASP.NET Core controller dedicated to API responses such as JSON or XML.
Why it matters: Knowing this convention lets you understand that the labels describe typical controller use rather than separate ASP.NET Core frameworks.
Key terms: Razor Pages, server-side rendered applications, minimal APIs, web API controllers, APIs, ASP.NET Core MVC framework, MVC controllers, HTML, JSON, XML
19.2 Your first MVC web application
This section creates the default MVC web app and explains how its controller actions, Razor views, and conventional routing differ from the equivalent Razor Pages app.
- MVC project creation: Describe how to create and run an MVC web application using the ASP.NET Core Web App (Model-View-Controller) template or the dotnet new mvc command, and identify that it produces a server-rendered HTML application using controllers and Razor views.
Why it matters: Creating the template gives you a working baseline for recognizing the MVC application structure and request flow. - MVC service and endpoint setup: Explain that an MVC app registers MVC controller and Razor view services with AddControllersWithViews() and maps its controllers as endpoints with MapControllerRoute(), rather than using AddRazorPages().
Why it matters: These two setup calls enable controller-based, server-rendered MVC requests in the application. - Controller actions and views: Explain that an MVC controller groups logically related action methods, that every nonabstract public controller method is an action unless marked with [NonAction], and that an action can return View() to produce a ViewResult that renders a Razor view. Describe that MVC passes data to the view as an explicit view model rather than exposing data as properties on a Razor Page PageModel.
Why it matters: Understanding actions, view results, and view models explains how MVC handles a request and generates an HTML response. - Conventional controller routing: Describe how MapControllerRoute uses a conventional route template with controller and action parameters, plus an optional id segment, to calculate which controller action handles a URL. Distinguish conventional routing, where one template can map to many controller endpoints, from explicit routing, where templates typically map to one endpoint.
Why it matters: Conventional routing explains why URLs such as /Home/Privacy and /products/view/123 reach different controller actions through one default route.
Key terms: ASP.NET Core Web App (Model-View-Controller) template, dotnet new mvc, MVC controllers, Razor views, AddControllersWithViews(), MapControllerRoute(), AddRazorPages(), Program.cs, MVC controller, action method
19.3 Comparing an MVC controller with a Razor Page PageModel
This section compares MVC controllers with Razor Page PageModels, showing that their request handling is largely equivalent apart from controller organization and view rendering.
- Controller and PageModel analogy: Explain how an MVC controller and its action methods correspond to a Razor Page PageModel and its page handlers in the MVC pattern.
Why it matters: Recognizing this correspondence lets you transfer Razor Pages knowledge to MVC controllers. - Shared request handling flow: Describe the common processing steps used by Razor Page handlers and MVC actions: dependency injection, model-bound parameters, interaction with the application model, and creation of a view model for a Razor view.
Why it matters: The shared flow means most request-processing techniques work similarly whether an application uses Razor Pages or MVC controllers. - Controller action aggregation: Describe why a ToDoController can group related action methods, such as actions for viewing a category, viewing an item, or creating an item, instead of representing only one page.
Why it matters: Grouping related operations in a controller is a key organizational difference when moving from page-focused Razor Pages to MVC.
Key terms: MVC controllers, actions, Razor Pages, PageModel, page handlers, MVC design pattern, dependency injection, model binding, application model, view model
19.4 Selecting a view from an MVC controller
This section explains how MVC controller actions return ViewResults to select, locate, and render Razor views with optional view models.
- ViewResult rendering flow: Explain how an MVC action method uses a ViewResult to render a Razor view, including the view name, optional view model, and Razor engine's generation of HTML.
Why it matters: A ViewResult is the bridge between a controller action's work and the HTML sent to the browser. - Razor view creation: Describe how to add an MVC Razor view and distinguish it from a Razor Page file by the absence of the @page directive.
Why it matters: MVC views use the same Razor features as Razor Pages, but they must be created as views rather than routable Razor Pages. - Convention-based view selection: Describe how View() without arguments selects a view by convention from the controller and action names, and how a supplied name or application-root-relative path overrides that convention.
Why it matters: Following MVC naming conventions reduces boilerplate and makes it easy for developers to predict which template an action renders. - View model delivery: Explain how an action passes an object as a view model with View(), and how the Razor view declares the matching type with @model and accesses it through Model.
Why it matters: A strongly shaped view model is the usual way to give a Razor view the data it needs to render safely and clearly.
Key terms: ViewResult, view model, Razor view, Razor engine, action method, Razor View - Empty, Views folder, .cshtml, @page directive, View()
19.5 Choosing between Razor Pages and MVC controllers
This introduction frames Razor Pages as the usual choice for server-rendered applications while clarifying that Razor Pages and MVC controllers are architecturally equivalent MVC approaches with different project organization.
- Default Razor Pages choice: State that the book generally recommends Razor Pages rather than MVC controllers for server-rendered applications, and explain that the section helps developers decide whether to retain familiar MVC controllers or switch.
Why it matters: This recommendation gives you a starting point when choosing an ASP.NET Core approach for a server-rendered website. - Architectural MVC equivalence: Explain that Razor Pages and MVC controllers are architecturally essentially equivalent because both use the MVC design pattern. Distinguish this from the more visible difference of how their files are organized in a project.
Why it matters: Recognizing their shared MVC foundation avoids treating Razor Pages as a fundamentally different or lesser web framework. - Razor Pages misconception correction: Describe the misconception that Razor Pages are equivalent to Web Forms, and state that this overlooks Razor Pages' underlying basis in the MVC framework.
Why it matters: Correcting this comparison helps developers from older ASP.NET backgrounds evaluate Razor Pages on its actual design.
Key terms: Razor Pages, MVC controllers, server-rendered applications, MVC design pattern, project structure, Web Forms, MVC framework
19.5.1 The benefits of Razor Pages
This section explains how Razor Pages differs from Web Forms and why its page-focused organization can be preferable to MVC controllers for many website features.
- Razor Pages versus Web Forms: Distinguish Razor Pages from ASP.NET Web Forms by explaining that Razor Pages follows the MVC design pattern and exposes normal web behavior, rather than hiding the web behind a stateful desktop-style model.
Why it matters: This distinction prevents you from rejecting Razor Pages based on the limitations of an older framework. - Page-focused file organization: Explain how Razor Pages co-locates a page's Razor view and nested PageModel file, while traditional MVC commonly separates controllers, views, and view models into folders organized by type.
Why it matters: Keeping the files for one page together reduces navigation between folders and makes page work easier to follow. - Page cohesion and controller bloat: Describe how a controller can accumulate many action methods and dependencies for a resource, whereas each Razor Page is a separate cohesive class for one page or feature, with page handlers serving the same role as action methods.
Why it matters: A page-focused design can keep individual features smaller and easier to reason about as an application grows. - Razor Pages use cases: Identify content-heavy sites with mostly static display and user data-entry forms as situations where Razor Pages is especially useful, while recognizing that Razor Pages retains separation of concerns and can coexist with MVC controllers and minimal APIs in one application.
Why it matters: Choosing Razor Pages for page and form workflows can avoid MVC complexity where controllers add little value.
Key terms: Razor Pages, Web Forms, MVC design pattern, stateful application model, stateless web application, Razor view, .cshtml, .cshtml.cs, PageModel, view model
19.5.2 When to choose MVC controllers over Razor Pages
This section identifies when MVC controllers are preferable to Razor Pages, when neither is the best fit, and how these approaches can coexist in one application.
- MVC controller selection scenarios: Explain the situations in which MVC controllers are a better choice than Razor Pages: when an app does not render HTML views, when converting an existing MVC application, and when extensive partial-page updates are needed.
Why it matters: Choosing the approach that fits the application avoids unnecessary rewrites and makes UI development easier. - Mixed Razor Pages and controllers: Describe how Razor Pages and MVC controllers can be used together in the same ASP.NET Core application, such as using Razor Pages for appropriate pages and controllers to return partial views.
Why it matters: You can choose the most suitable UI approach per feature instead of committing the whole application to one pattern. - Alternatives to UI frameworks: Distinguish cases where Razor Pages and MVC controllers are not the best tools: consider minimal APIs for performant JSON APIs, gRPC for server-to-server or nonbrowser clients, WebSockets or SignalR for real-time functionality, and Blazor for interactive client-side applications.
Why it matters: Matching the communication and interaction model to the application can avoid the overhead and limitations of an HTML UI framework.
Key terms: MVC controllers, Razor Pages, HTTP API, web API controllers, partial page updates, partial view results, minimal APIs, JSON API, gRPC, WebSockets
19.6 Summary
This summary recaps how MVC controllers are configured, routed, and used to render views, and when they differ from Razor Pages.
Where this is used later
- Creating your first web API project (chapter 20) · Creating a web API project uses the web API controller option mentioned here.
- (chapter intro) (chapter 20) · The distinction between Razor Pages and MVC controllers.
- Applying the MVC design pattern to a web API (chapter 20) · Applying MVC to a web API relies on the same unified controller framework.
- Summary (chapter 21) · MVC controllers and their actions as targets for application behavior.
- (chapter intro) (chapter 24) · MVC controllers as an alternative application model.
- Understanding the MVC filter pipeline (chapter 21) · The MVC filter pipeline operates around controller action execution and results.
- Attribute routing: Linking action methods to URLs (chapter 20) · Attribute routing is presented as the explicit-routing alternative for controller actions.
- Generating a response from a model (chapter 20) · Web API controllers contrast ViewResult-based HTML rendering with generating API responses from models.
Concepts explained in this chapter
- controllerA web API controller is an ASP.NET Core controller that handles HTTP API requests through action methods and produces machine-readable responses.
- web API action methodAn API controller action is a method on a web API controller that handles a request and produces an HTTP result.
- ViewResultViewResult is an ASP.NET Core MVC action result that renders a Razor view using an optional view name and model.
- Razor syntaxA Razor view is a server-rendered template that combines markup with embedded C# expressions and accesses data supplied by an application component.
- view modelA view model is an object or data structure containing the information a user-interface view requires to render a response.
- Razor PagesA Razor Page is an independently addressable ASP.NET Core page endpoint typically composed of a .cshtml view file and an associated PageModel class.
- viewA view is an MVC presentation component that transforms supplied application data into rendered user-interface output such as HTML.
- AddControllersWithViewsAddControllersWithViews is an ASP.NET Core service-registration method that adds MVC controller and view services to an application's dependency injection container.
- routingRouting is the mechanism that maps incoming requests to application endpoints or handlers.
- handlerA handler is an application component that receives a framework-dispatched request or event and performs the corresponding processing.
- MapControllerRouteMapControllerRoute is an ASP.NET Core endpoint-mapping method that maps MVC controllers using a conventional route template.
- web applicationA web application is software that provides functionality to users through web technologies and a browser or other web client.
- ASP.NET Core MVCASP.NET Core MVC is the ASP.NET Core web framework implementation of the Model-View-Controller pattern for building web applications.
- server-side renderingServer-side rendering is the process of generating HTML on the server before sending it to a client.
- Model–view–controllerModel-View-Controller is an application architecture pattern that separates domain data, presentation, and request-handling control logic.
- templateA software template is a predefined starting structure containing code and configuration for building an application.
- application modelAn application model is an architectural component that encapsulates the non-user-interface parts of an application, including domain models, services, and data-access interactions.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
