In so many scenario splitting the C# code from html file will be good decision like unit testing or code re-usability in blazor project.
We can do this task in blazor using two approach
1. Partial files approach
2. Base class approach
Partial files approach
In this approach we create the same class name as component name. Suppose i have component test3.razor
then i have to create Test3.cs partial class
test3.razor file
@page "/test3" <h3>This is test3 page</h3> <p>Message from C# Code Block: @msg</p> <button @onclick="SayHello">Click Here</button>
Test3.cs partial class
namespace BlazorApp2.Pages { public partial class Test3 { public string msg = string.Empty; private void SayHello() { msg= "Hello Blazor"; } } }
2. Base class approach
In this approach the create the base class which will inherit the ComponentBase class.
using Microsoft.AspNetCore.Components; namespace BlazorApp2.Pages { public class Test3Base: ComponentBase { public string msg = string.Empty; public void SayHello() { msg= "Hello Blazor"; } } }
In Test3.blazor file use @inherits Test3Base syantax.
@inherits Test3Base @page "/test3" <h3>This is test3 page</h3> <p>Message from C# Code Block: @msg</p> <button @onclick="SayHello">Click Here</button>