Author : MD TAREQ HASSAN | Updated : 2020/09/08
Blazor Component
- A component in Blazor is an a self-contained chunk of user interface (UI), such as a page, dialog, or data entry form
- component class is usually written in the form of a Razor markup page with a .razor file extension (components in Blazor are formally referred to as Razor components)
- Components are .NET classes built into .NET assemblies that:
- Define flexible UI rendering logic
- Handle user events
- Can be nested and reused
- Can be shared and distributed as Razor class libraries or NuGet packages
- Razor allows you to switch between HTML markup and C# in the same file with IntelliSense support
- Unlike Razor Pages and MVC, which are built around a request/response model, components are used specifically for client-side UI logic and composition
- Links
Single File Approach
- Markup and logic (C# + HTML) in the same file
- C# code in
@code { ... }
block - It will eventually become tedious to maintain due to constant scrolling between between markup and logic
- While a single file approach provides benefits in its simplicity, and is great for small components, it simply doesn’t scale well
- Avoid for complex component
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?
- Keep code and presentation separated
- Use dependency injection
- Avoid repeating code
- Loose coupling
- Scalability
Naming convention:
- razor file:
Foo.razor
- code behind C# class file:
Foo.razor.cs
- C# class name:
class FooBase {...}
- we are using
[componentName]Base
for class name because razor markup will be parsed into a component class and we are gonna inherit from code behind class (so, code behind class is base class)
Code behind class is a standard .NET class and inherited by (parsed) razor. Imagine as following
.razor
is parsed into partial class- code behind
.cs
is partial class - resulting class is combination of both and therfore
.razor
has access to properties in.cs
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