skip to content

In ASP.NET Core MVC, which files does return View() search for, and when is a view in Views/Shared used instead?

level: juniorimportance: must knowfreq 68%

answer

  1. view name defaults to the action route value
  2. /Views/{controller}/{view}.cshtml first
  3. then /Views/Shared/{view}.cshtml
  4. a path ending in .cshtml skips the search
  5. InvalidOperationException lists searched locations

basics

~20 s

View() takes the view name from the action's route value and searches /Views/{controller}/{name}.cshtml, then /Views/Shared/{name}.cshtml (plus /Pages/Shared when Razor Pages are registered). A Shared view serves any controller that has no view of that name.

solid answer

~40 s

When an action returns `View()` with no name, the `ViewResultExecutor` uses the `action` route value as the view name, so `DetailsAsync` looks for `Details` because MVC trims the `Async` suffix by default, and `[ActionName("Show")]` looks for `Show`. The Razor view engine then tries `RazorViewEngineOptions.ViewLocationFormats` in order: `/Views/{1}/{0}.cshtml` (controller folder) and `/Views/Shared/{0}.cshtml`; registering Razor Pages adds `/Pages/Shared/{0}.cshtml`. Areas get `/Areas/{2}/Views/{1}/`, `/Areas/{2}/Views/Shared/` and `/Views/Shared/`. The first match wins, so a controller-specific view overrides a shared one of the same name. `View("Card")` changes only the name; `View("~/Views/Listings/Card.cshtml")` or any path ending in `.cshtml` is used as given. If nothing matches, MVC throws `InvalidOperationException`: "The view 'Details' was not found. The following locations were searched:" followed by each path.

code

csharp · 15 lines
csharp
public class ListingsController(IListingStore store) : Controller
{
    // action name "Details" -> /Views/Listings/Details.cshtml, then /Views/Shared/Details.cshtml
    public async Task<IActionResult> DetailsAsync(int id, CancellationToken ct)
    {
        var listing = await store.FindAsync(id, ct);
        return listing is null ? NotFound() : View(listing);
    }

    // explicit name: /Views/Listings/Gallery.cshtml, then Shared
    public IActionResult Photos(int id) => View("Gallery", id);

    // explicit path: no search at all
    public IActionResult Print(int id) => View("~/Views/Print/Listing.cshtml", id);
}

go deeper

for a junior

Recall the default lookup: the controller's folder under Views first, then Views/Shared, with the view named after the action.

for a middle

Explain how the action route value, SuppressAsyncSuffixInActionNames and [ActionName] decide the name, and how areas and Razor Pages extend the location list.

for a senior

Diagnose 'view not found' from the searched-locations list and keep overrides predictable by avoiding hard-coded paths and misplaced shared views.

for a principal

Choose a folder convention (by controller, by feature, by area) for a large site and enforce it with location formats rather than per-action paths.

## From action to view name A controller action that renders HTML returns a `ViewResult`, usually through `Controller.View(...)`. The overloads decide two things: the **view name** and the **model**. - `View()` and `View(model)` leave the name null. When the result executes, `ViewResultExecutor` falls back to the **`action` route value**, which is the action name MVC registered, not necessarily the C# method name. - Because `MvcOptions.SuppressAsyncSuffixInActionNames` defaults to `true`, a method named `DetailsAsync` has the action name `Details`, and its default view is `Details.cshtml`. - `[ActionName("Show")]` on the method changes the action name, so the default view becomes `Show.cshtml`. - `View("Gallery", model)` asks for a different view by name. ## The search order The Razor view engine expands the name through `RazorViewEngineOptions.ViewLocationFormats`, where `{0}` is the view name, `{1}` the controller name and `{2}` the area name. For a `ListingsController` in a real-estate site, `return View(listing);` from `Details` tries: 1. `/Views/Listings/Details.cshtml` 2. `/Views/Shared/Details.cshtml` 3. `/Pages/Shared/Details.cshtml`, only when `AddRazorPages()` (or `AddMvc()`) registered Razor Pages For an action in an area, `AreaViewLocationFormats` are used instead: `/Areas/{2}/Views/{1}/{0}.cshtml`, `/Areas/{2}/Views/Shared/{0}.cshtml`, then `/Views/Shared/{0}.cshtml`. The first existing view wins. That is how **Views/Shared** works: it is the fallback for every controller, which is why it holds `_Layout.cshtml`, `Error.cshtml` and shared partials, and why a controller can override a shared view by adding one with the same name to its own folder. ## Names versus paths | Call | What is searched | |---|---| | `View()` | location formats with the action name | | `View("Gallery")` | location formats with `Gallery` | | `View("~/Views/Listings/Gallery.cshtml")` | exactly that app-relative path | | `View("Gallery.cshtml")` | treated as a path: relative to the executing view if there is one, otherwise to the app root (`/Gallery.cshtml`); never run through the formats | The engine treats a name starting with `~` or `/`, or ending in `.cshtml`, as a **path**. Everything else is a **name** to expand. ## When nothing is found If no location exists, `ViewResultExecutor` throws `InvalidOperationException` with the message "The view 'Details' was not found. The following locations were searched:" and one line per path. Reading that list is the fastest diagnosis: it shows the controller and area names the engine actually used, which exposes a misspelt folder, a missing area attribute, or an `Async` suffix you expected to be part of the name. ## Areas in practice A listings site with an `Agents` area marks `ProfileController` with `[Area("Agents")]`. Its `Index` action then searches `/Areas/Agents/Views/Profile/Index.cshtml`, `/Areas/Agents/Views/Shared/Index.cshtml` and finally the site-wide `/Views/Shared/Index.cshtml`. Forgetting `[Area]` is a classic cause of "view not found": the engine uses the plain `ViewLocationFormats`, and the error message lists `/Views/Profile/Index.cshtml` instead of the area folder, which is the clue. Each area normally carries its own `_ViewStart.cshtml` and `_ViewImports.cshtml` in its `Views` folder, because those files are discovered along the view's own path. ## Lookup is cached and works on compiled views The Razor SDK compiles `.cshtml` files into the application at build time, and the engine resolves paths against those compiled views. Successful and failed lookups are stored in the engine's view lookup cache, keyed by view name, controller, area and main-page flag (plus any values from view location expanders), so the search runs once per combination and is reused while the entry stays cached (a 20-minute sliding expiration), not on every request. ## Unit-testing the choice of view Because the name is resolved when the result **executes**, a unit test that calls the action directly sees `ViewResult.ViewName == null` for `return View(model);`. Assert on the model and, where it matters, return an explicit name; verify that the file really exists with an integration test through `WebApplicationFactory`, which renders the page and fails with the searched-locations message if the view is missing. ## Common mistakes - **Expecting the method name.** `GetDetailsAsync` with no attribute looks for `GetDetails.cshtml`, not `Details.cshtml`. - **Putting a controller-specific view in Shared** and then wondering why another controller with the same action name renders it. - **Returning `View()` from a `ControllerBase`-derived API controller**: `View` exists only on `Controller`, and the view services come from `AddControllersWithViews()`. - **Hard-coding paths everywhere.** `View("~/Views/...")` works but defeats overriding; reserve it for the rare cross-controller case. Changing *where* the engine looks, for themes or feature folders, is done with `IViewLocationExpander` or by editing `ViewLocationFormats`, not by hard-coding paths in actions.

  • Why does a shared Error.cshtml render for every controller's error action?
    Each controller's `/Views/{controller}/Error.cshtml` is searched first and does not exist, so the engine falls through to `/Views/Shared/Error.cshtml`. Adding `/Views/Listings/Error.cshtml` would override it for `ListingsController` only.
  • How do you reorganise views into feature folders without hard-coding paths in every action?
    Add location formats once, either by inserting into `RazorViewEngineOptions.ViewLocationFormats` (for example `/Features/{1}/{0}.cshtml`) or with an `IViewLocationExpander` when the location depends on the request. Actions keep returning `View()`.

  • View() looks for a file named after the C# method, Async suffix included.
  • Views/Shared is searched before the controller's own folder.
  • View("Gallery") and View("Gallery.cshtml") are searched the same way.
  • The engine scans the disk for .cshtml files on every request.
  • A missing view silently renders an empty page.