You can create view markup and C# code logic in separate files when creating a Blazor component.
Let's move the C# code logic from Counter.cshtml file to seperate code behind class.
using Microsoft.AspNetCore.Blazor.Components;
namespace BlazorApplication
{
public class CounterClass : BlazorComponent
{
public int CurrentCount { get; set; }
public void IncrementCount()
{
CurrentCount += 5;
}
}
}
The Counter.cshtml file will use the properties and methods from the code behind class just by adding @inherits CounterClass
.
@page "/counter"
@inherits CounterClass
<h1>Counter</h1>
<p>Current count: @CurrentCount</p>
<button class="btn btn-primary" onclick="@IncrementCount">Click me</button>
Blazor compiler generates class for all the view pages with the same class name as the page name, so here, a specified base class cannot have the same name as Razor View, otherwise, it would cause a compile-time error.
Now when the Click me button is pressed, the counter is incremented by 5.