If you create a new Blazor Web App project (you can choose any rendering mode and any rendering location), then in the template, e.g. in the Counter.razor component, you can see that in one file we have both razor code, which is mainly HTML, and also typical C# code at the bottom. So we mix typical frontend code with so-called code-behind in one file, and this is not a good practice. We should separate responsibilities here and each part should be in a separate file. In this article, I will show you how to fix it in Blazor.
Counter.razor
This is what our initial code looks like:
@page "/counter"
<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++;
}
}
Separation of responsibilities
Fortunately, in Blazor we can easily separate responsibilities in our classes. We can easily separate front-end code from C# code, so that everything follows best practices for writing code.
To do this, we need to add a new file with the same name as the component name, only with the extension razor.cs.
So let's add a new file in this case called: Counter.razor.cs
namespace BlazorApp.Client.Pages
{
public class Counter
{
}
}
At this point, Visual Studio reports an error to us and to correct it we need to mark our class with the keyword - partial.
namespace BlazorApp.Client.Pages
{
public partial class Counter
{
}
}
At this point the error is gone. We can move the C# code from the view to the C# class. And this is what our files will look like.
Counter.razor
@page "/counter"
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
Counter.razor.cs
namespace BlazorApp.Client.Pages
{
public partial class Counter
{
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
}
We do not have any bug and if you run the application you will see that everything works the same as before.
Summary
Everything works and this code is in line with best practices and this is how we will create our views and code in C# when developing applications in Blazor.
The file with the .razor extension only will contain the view, and the file with the .razor.cs extension will contain the application logic, i.e. the C# code.
Blazor School
By the way, if you would like to learn Blazor from the inside, consider joining my online training - Blazor School (more information here - https://blazor-school.com/).