How to split the C# code from Blazor Component ?


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>

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.