| by Achyut Kendre | No comments

What is Directives in Razor Syntax? How to use it using _ViewImports.cshtml in ASP.NET Core MVC?

ASP.NET Core 3.1

Directives in Razor Syntax

ASP.NET Core Razor Syntax provides you few commands those can be used in Razor Page or View called Directives which adds some additional functionality in page. You can use them using syntax –

@directivename parameters

Razor directives are represented by implicit expressions with reserved keywords following the @ symbol. A directive typically changes the way a view is parsed or enables different functionality. Few of them are –

  • @addTagHelper
  • @inherits
  • @using
  • @namespace
  • @inject
  • @model
  • @removeTagHelper etc.

What is _ViewImports.cshtml?

In ASP.NET Core MVC Application, the _ViewImports.cshtml file provides a mechanism to include the directives globally for Razor Pages so that we don’t have to add them individually in each and every page.

The ViewImports file is a place where we can write code and place common directives to pull in namespaces that our views need.

If there are namespaces that we commonly use in our views, we can have using directives appear once in our ViewImports file instead of having using directives in every view or typing out the full namespace of a class.