Author : MD TAREQ HASSAN | Updated : 2020/09/08

Blazor Component

Single File Approach

Pages/Counter.razor

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

Code-Behind Approach

Once our component requires complex markup or logic it’s easy to get lost in the large file and/or confused by two different ways of expressing code. Keeping the code and UI separate supports all sorts of best practices

Why Code-Behind?

Naming convention:

Code behind class is a standard .NET class and inherited by (parsed) razor. Imagine as following

Pages/Counter.razor

@page "/counter"
@inherits CounterBase

<h1>Counter</h1>

<p>Current count: @CurrentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

Pages/Counter.razor.cs

public class CounterBase: ComponentBase
{
	protected int CurrentCount { get; set; }

	public void IncrementCount()
	{
		CurrentCount++;
	}
}

Note: Code behind class properties should be protected or public so that razor markup can access them