Directives on Blazor Server

Directives are special keywords that come after the "@" symbol that adds additional behaviour to elements on your Blazor Server website. With Blazor Server's built-in directives, you can manage many aspects of user interactions. Some of the common uses of directives are:

  • Routing.
  • Implement interface.
  • Dependency injection.
  • Import namespaces.
Download the example for a working example containing the code snippets in this guide.

The different types of Blazor Server directives are as follows:

  1. Compiling directives. This type of directive manipulates how a Razor Component is compiled.
  2. DOM interactive directives. This type of directive binds properties to elements and interacts with the DOM element.
  3. Utilities directives. This type of directive adds various features to a component and makes components more useful.
Note: In .NET 5, directives are not customizable or creatable. You can only use pre-built directives but not customize them or create your own directives.
Directive identifier Description Type
@attribute Attach a dictionary of attributes to the element DOM interactive
@on<event> Attach the event handlers to the element's event DOM interactive
@<C#-keyword>, @{<C# Code>},@(<C# Code>) Inject C# code to HTML template Utilities
@bind-<attribute>:<event> Create a 2-ways binding to an element attribute DOM interactive
@key Set a unique identifier for an element DOM interactive
@ref Refer the element to an C# instance DOM interactive
@inherits Specify the base class for a component Compiling
@inject Inject an instance into a component Utilities
@namespace Specify the namespace for a component Compiling
@implements Specify the interface for a component Compiling
@page Specify the route and parameter to a component Utilities
@preservewhitespace Remove all redundant white spaces from an element Compiling
@section Define a section, not available for Razor Component. Not commonly used in Blazor. N/A
@typeparam Specify a generic class for a component Compiling
@functions Deprecated, use @code instead N/A
@code Add C# code that defines the component's logic, state, and behavior DOM interactive
@layout Specify the layout for a component Compiling
BLAZOR SCHOOL
Designed and built with care by our dedicated team, with contributions from a supportive community. We strive to provide the best learning experience for our users.
Docs licensed CC-BY-SA-4.0
Copyright © 2021-2025 Blazor School
An unhandled error has occurred. Reload 🗙