The relationship between Razor and Blazor
The relationship between Razor and Blazor is closer than we think! The name "Blazor" comes from "Browser + Razor", because Blazor has the possibility of executing the views on the browser, while Razor is strictly on the server-side.
Blazor uses Razor based components (the components mentioned previously in the article), these components can be whole pages or small elements like buttons, this way we can use C#, HTML, and CSS together.
The file extension .razor indicates that the file is a Razor component class, where we can write C#, HTML, and CSS.
These component classes go beyond the typical functionalities of Razor, and here we can define variables and methods that can be called by the client-side of the application. Because these classes are Razor, we can use all of its features, like the use the parameter '@' to write C# code.
The following example, taken from the official Blazor documentation, shows the basic structure of a Razor component class (file name: Dialog.razor):
-
<div>
<h1>@Title</h1>
@ChildContent
<button @onclick="OnYes">Yes!</button>
</div>
@code {
[Parameter]
public string Title { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
private void OnYes()
{
Console.WriteLine("Write to the console in C#! 'Yes' button was selected.");
}
}
As we can see in the example, everything after '@' is a C# variable or method. The two exceptions are:
- @code { … } - behaves like a standard C# class and everything defined inside can be used in the HTML part;
- @onclick - is one of the many Blazor primitives functions. This one specifies the behaviour of an on click event, in this case, calls the method OnYes.
After creating this component (Dialog.razor), we have to call it in other pages to use it, by simply writing <Dialog>, rendering the Dialog.razor inside the other page/component. We can even pass parameters to the components, and in this scenario, we need to use the tag [Parameter] as seen in the example code.