liveBook · Manning

Code-behind file

As explained in ASP.NET Core in Action, 3e

A code-behind file is a source file paired with a declarative user-interface file that contains the associated application logic or model class.

A code-behind file is the C# file paired with a declarative Razor view. In Razor Pages, the .cshtml.cs file contains the associated PageModel, request handlers, and interactions with application services. section 17.2.1 section 13.1.4

A Razor Page commonly separates responsibilities this way:

  • The .cshtml file contains the Razor template and the @page directive that makes it routable. section 17.2.1
  • The .cshtml.cs file contains a PageModel derived from PageModel, commonly with handlers such as OnGet. section 13.1.4
  • The @model directive identifies which PageModel belongs to the view; matching filenames alone do not create the association. section 17.2.1
  • Handlers respond to HTTP verbs, can use dependency injection, and return rendered HTML or an IActionResult. section 13.1.4

A simple Privacy page

Privacy.cshtml.cs can define a PrivacyModel with an injected ILogger<PrivacyModel> and an empty OnGet method. A GET request reaches OnGet, then the associated Razor template renders the HTML response. section 13.1.4

@page
@model ToDoItemModel

Use the @page and @model directives together to mark a Razor Page and connect it to its PageModel. section 17.2.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains file roles, directive-based association, handler execution, dependency injection, and response generation.
Examples
Uses PrivacyModel, Privacy.cshtml.cs, ILogger, OnGet, and the @page and @model directives.
What you can do after
Apply it via Razor Pages to connect a .cshtml view with a PageModel and handle requests.
How it connects
Connects Razor Pages with Razor views, PageModel, page handlers, routing middleware, HTTP verbs, and dependency injection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.