liveBook · Manning

Razor using directive

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

A Razor using directive imports a namespace so its types can be referenced without namespace qualification in a Razor file.

A Razor using directive imports a namespace so views can reference its types without repeating fully qualified names. Place it in _ViewImports.cshtml to make the import available to views in that folder hierarchy, or place it directly in one .cshtml file for local use. section 21.3.1

Importing a view-model namespace

Create Views/_ViewImports.cshtml with @using WebApp.Models. A view can then declare @model Product instead of @model WebApp.Models.Product. The same approach appears in SportsStore with @using SportsStore.Models; that file also contains an independent @addTagHelper directive. section 21.3.1 section 7.1.6

Listing 21.17 The contents of the _ViewImports.cshtml file in the Views folder
@using WebApp.Models

Use the complete _ViewImports.cshtml listing to verify the namespace import syntax and its placement in the Views folder. section 21.3.1

After the import is available, remove the namespace qualification from the view’s model declaration. Save the view and request the application URL to verify the rendered result. An editor warning may appear while the file is being configured, but the surrounding setup can resolve it. section 21.3.1 section 7.1.6

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

How deep it goes
Demonstrates project-level and view-level placement, but does not explain Razor compilation internals.
Examples
Uses WebApp.Models with Product in Watersports.cshtml and SportsStore.Models in a shared imports file.
What it assumes
Assumes basic Razor views and namespaces while teaching the imports-file setup from the file-creation step.
What you can do after
Apply it via _ViewImports.cshtml or an individual .cshtml file to shorten type declarations and verify rendered views.
How it connects
Connects Razor views with namespaces, view models, the Razor view engine, layouts, and tag helpers.

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.