liveBook · Manning

Razor view convention

As explained in Pro ASP.NET Core 7, Tenth Edition

The Razor view convention is the MVC convention that locates a view by combining the action name and controller name with predefined view folders and a file extension.

When an MVC action calls View, the Razor view engine searches for a .cshtml file matching the action name. It first checks the controller-specific Views folder, then Views/Shared for reusable views. section 21.2.2

HomeController.Index

An Index action on Home returns View(product). The convention searches Views/Home/Index.cshtml first, then Views/Shared/Index.cshtml. The controller name contributes Home after removing the Controller suffix. section 21.2.2

Listing 21.5 The contents of the HomeController.cs file in the Controllers folder
using Microsoft.AspNetCore.Mvc;
using WebApp.Models;

namespace WebApp.Controllers {

   public class HomeController : Controller {
       private DataContext context;
               
       public HomeController(DataContext ctx) {
           context = ctx;
       }
               
       public async Task<IActionResult> Index(long id = 1) {
           return View(await context.Products.FindAsync(id));
       }
   }
}

Inspect the controller action that retrieves a product and returns it through View, triggering conventional view lookup. section 21.2.2

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains action-name matching, .cshtml extension, controller folders, and the Views/Shared fallback.
Examples
Uses HomeController.Index, a product model, Views/Home/Index.cshtml, and Views/Shared/Index.cshtml.
What it assumes
Assumes familiarity with controller actions and teaches how returning View connects them to Razor files.
What you can do after
Evaluate view resolution by predicting which conventional .cshtml path an action will search first.
How it connects
Connects controllers, action methods, ViewResult, routing, Razor view engine, and shared views.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.