Blazor Code Behind
If you have been using Blazor, you are probably familiar with .razor
files that contain both the UI markup and the code to support it.
The template from Microsoft for a new Blazor Server application creates a Pages/Counter.razor
file that looks like this -
@page "/counter"
@rendermode InteractiveServer
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
If you want to separate the code from the markup, you can do that by creating a code-behind file and altering the .razor
file slightly.
Start by creating a new file called Counter.razor.cs
in the same directory as Counter.razor
.
Here are the important things -
- The class in the code-behind file must be
partial
. - The file must have the same name as the
.razor
file, with.cs
appended. e.g.Counter.razor.cs
. - The namespace must match the namespace of the
.razor
file, even though it is not explicitly stated in the.razor
file. In the case ofCounter.razor
in a Blazor sample application, the namespace isYourAppName.Components.Pages
. - The
.razor
file must include@rendermode InteractiveServer
.
Here is what the Counter.razor.cs
file looks like -
namespace YourAppName.Components.Pages;
public partial class Counter
{
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
The .razor
no longer has the @code
block.
@page "/counter-with-code-behind"
@rendermode InteractiveServer
<PageTitle>Counter with Code Behind</PageTitle>
<h1>Counter with Code Behind</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
To avoid ambiguity, you can also add a namespace to the .razor
file like this -
@namespace YourAppName.Components.Pages
That’s it. You can now separate your code from your markup in Blazor applications. The thing that caught me out was the missing namespace in the code behind. If you don’t get that right, you will get a compile error.