Skip to main content

Split HTML And C# Code In Blazor Using Either Partial Class Or ComponentBase Class



By default Blazor component file consists of HTML code and C# code under the single file. For better coding standards we can split HTML code and C# code to separate files using concepts like:
  1. Partial Class
  2. ComponentBase Class

Create Sample Blazor Server Application:

Blazor Single Page Application comes with two types of templates like (1) Blazor Server, 
(2) Blazor Web Assembly. Let's create a Blazor Server templated sample application to understand to split the *.razor(Blazor file extension) files. 

Using Visual Studio 2019 using a rich user interface we can create Blazor Templated application very easily. But for this sample, I'm using .Net Core CLI(Command Line Interface) with Visual Studio Code IDE. Click to know how to use Visual Studio Code Editor for .Net Core applications.
.Net Core Blazor Server CLI Command:-

dotnet new BlazorServer -n Your_Application_Name
Blazor project preview:-
Open a command prompt whose path needs to be pointed to the Startup.cs file in our project(which application folder root path), then run the below .NET CLI command to start Blazor application.
CLI run Command:-

dotnet watch run
Application preview:-

Let's examine the Counter Component Code default sample Blazor 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++;
    }
}
  • #L3 - #L7: These lines contain HTML code with model binding.
  • #L9 - #L16: These lines contain C# code.
  • By default Blazor component single file is a combination of HTML and C# code.
In upcoming steps, we going to split this Counter.razor to separate files using Partial Class and ComponentBase Class.

Why Split *.razor File?:

  1. Code separation is like a fundamental rule in programming.
  2. Separating the Html Code and C# makes the development of Blazor Component easy and maintainable.
  3. Makes C# Code Testable. 

Partial Class Implementation:

Partial Class is a feature of implementing a single class into multiple files. So now we will maintain the Html code in Counter.razor file and C# code in  Counter.razor.cs file. Counter.razor.cs file acts as a code-behind file for Counter.razor file. While writing class in Counter.razor.cs file we explicitly mention a partial keyword, but Counter.razor  Blazor file with Html Content, but .Net Compiler is good enough to read Counter.razor as a partial class, so on code compilation single Counter.cs file will be generated.
Let's create a Counter.razor.cs file and inject all c# code into it as below.
Pages/Counter.razor.cs:
namespace SplitFileSample.Pages
{
    public partial class Counter
    {
        private int currentCount = 0;

        private void IncrementCount()
        {
            currentCount++;
        }
    }
}
#L3: class declared with a partial keyword.
#L5 - #L10: c# code copied from Counter.razor file.

By chance, if we miss declaring partial keyword in class .Net compiler intelligent enough to notify us by failing the project compilation as below.

Visual Studio Code editor good enough to track the reference of Counter.razor.cs file members on Counter.razor file.
Finally Counter.razor file contains only HTML or Razor Code.
Pages/Counter.razor:
@page "/counter"

<h1>Counter</h1>

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

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
That's all we have successfully used partial class implementation for code separation.

ComponentBase Class Implementation:

ComponentBase is a class that hooked up with all component life cycles of a Blazor Component. ComponentBase class is derived from the library Microsoft.AspNetCore.Components. This approach works with the class inheritance technique.

In this approach Counter.razor.cs file declares class like CounterBase.cs which inherits ComponentBase class. Finally Counter.razor file inherits CounterBase.cs class.
Let's implement the inheritance of ComponentBase class to CounterBase.cs file as below.
Pages/Counter.razor.cs:
using Microsoft.AspNetCore.Components;

namespace SplitFileSample.Pages
{
    public class CounterBase : ComponentBase
    {
        protected int currentCount = 0;

        protected void IncrementCount()
        {
            currentCount++;
        }
    }
}
  • #L1: To inherit ComponentBase class added the reference of the library name Microsoft.AspNetCore.Components
  • CounterBase class can override the life cycle methods that are inherited from ComponentBase class.
  • #L7, #L9: At these lines, we have used protected access specifiers, because of Counter.razor(inheritance in the upcoming steps) file inherits CounterBase. So the methods or properties which need to expose in Counter.razor file then their minimum access specifier should be protected from this we can draw a conclusion like we can't use private access specifier.
Reason to create a class name as CounterBase in Counter.razor.cs file - Class name can't be created as Counter. Because of Counter.razor file on compilation generates a partial class with the name Counter, in that case, if we create a class name as Counter in Counter.razor.cs file compiler throws an error like 'there is an existing partial class with name Counter, so please create your new class as partial'(this error simple violation of partial class rules). So we create a class name as CounterBase in Counter.razor.cs, here class name add tail with word 'Base' that is like a naming convention of representing like it is parent class for Counter.razor file.

Finally, inherit CounterBase class into Counter.razor file as below.
Pages/Counter.razor:
@inherits CounterBase
<h1>Counter</h1>

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

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
At #L1 inherited CounterBase class.

That's it we completed ComponentBase class implementation as well.

Wrapping Up:

Hopefully, I think this article delivered some useful information about Partial Class and CounterBase class in Blazor Components. I love to have your feedback, suggestions, and better techniques in the comment section below.

Follow Me:

Comments

  1. When to use one or the other? Any advantages or disadvantages?

    ReplyDelete
    Replies
    1. Hi Moroni,
      They are like 2 techniques blazor providing both are at equal level, no advantage over other. My prefered approach was Partial Class because it more work like code behind file approach in .net technologies.

      Delete
  2. Hi Naveen,

    One advantage of the base class approach vs partial class is you can have multiple layers of inheritance (a sequence of base classes before you get to the last in the chain eg

    ComponentBase
    B1 : ComponentBase
    B2 : B1
    B3 : B2
    Component : B3

    if for example you have things common you want to share across multiple components in a library. For simple cases without the above need, I would also prefer the partial approach. Just worth bearing in mind as this is one scenario I can think of where it pays to go one way over the other.

    ReplyDelete
  3. Thanks for the article. I've started implementing both solutions. I have a standard base class that all pages can implement with common functions, as well as all authentication variables. And I use a partial class for all page specific functions and variables.

    ReplyDelete
  4. The reason to separate the codes that have the most weight is:
    "Makes the C # code testable", great.

    ReplyDelete

Post a Comment

Popular posts from this blog

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually

.Net5 Web API Redis Cache Using StackExchange.Redis.Extensions.AspNetCore Library

In this article, we are going to explore the integration of Redis cache in .Net5 Web API application using the 'StackExchange.Redis.Exntensions' library. Note:- Microsoft has introduced an 'IDistributedCache' interface in dotnet core which supports different cache stores like In-Memory, Redis, NCache, etc. It is simple and easy to work with  'IDistributedCache', for the Redis store with limited features but if we want more features of the Redis store we can choose to use 'StackExchange.Redis.Extensions'.  Click here for Redis Cache Integration Using IDistributedCache Interface . Overview On StackExchange.Redis.Extnesions Library: The 'StackExchange.Redis.Extension' library extended from the main library 'StackExchange.Redis'. Some of the key features of this library like: Default serialization and deserialization. Easy to save and fetch complex objects. Search key. Multiple Database Access Setup Redis Docker Instance: For this sampl

Usage Of CancellationToken In Asp.Net Core Applications

When To Use CancellationToken?: In a web application request abortion or orphan, requests are quite common. On users disconnected by network interruption or navigating between multiple pages before proper response or closing of the browser, tabs make the request aborted or orphan. An orphan request can't deliver a response to the client, but it will execute all steps(like database calls, HTTP calls, etc) at the server. Complete execution of an orphan request at the server might not be a problem generally if at all requests need to work on time taking a job at the server in those cases might be nice to terminate the execution immediately. So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp.NetCore MVC application. Note: The sample codes I will show in

Endpoint Routing In Asp.Net Core

How Routing Works In  Core 2.1 And Below Versions?: In Asp.Net Core routing is configured using app.UseRouter() or app.UseMvc() middleware. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); Here in Dotnet Core version 2.1 or below versions on the execution of route middleware request will be navigated appropriate controller matched to the route. An operation or functionality which is dependent on route URL or route values and that need to be implemented before the execution of route middleware can be done by accessing the route path from the current request context as below app.Use(async (context, next) => { if(context.Request.Path.Value.IndexOf("oldvehicle") != -1) { context.Response.Redirect("vehicle"); } else { await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "vehicleRoute", template: "vehicle", defaul

Asp.Net Core MVC Form Validation Techniques

Introduction: Form validations in any applications are like assures that a valid data is storing on servers. All programing frameworks have their own individual implementations for form validations. In Dotnet Core MVC application server-side validations carried on by the models with the help of Data Annotations and the client-side validations carried by the plugin jQuery Unobtrusive Validation. jQuery Unobtrusive Validation is a custom library developed by Microsoft based on the popular library  jQuery Validate . In this article, we are going to learn how the model validation and client-side validation works in Asp.Net Core MVC Application with sample examples. Getting Started: Let's create an Asp.Net Core MVC application project using preferred editors like Microsoft Visual Studio or Microsoft Visual Studio Code. Here I'm using Visual Studio. Let's create an MVC controller and name it as 'PersonController.cs' and add an action method as bel

NestJS File Upload

In this article, we are going to understand the steps to create a file uploading endpoint in the NestJS application. Key Features In NestJS File Upload: Let us know some key features of NestJS file upload before implementing a sample application. FileInterceptor: The 'FileInterceptor' will be decorated on top of the file upload endpoint. This interceptor will read single file data from the form posted to the endpoint. export declare function FilesInterceptor(fieldName: string, localOptions?: MulterOptions): Type<NestInterceptor>; Here we can observe the 'fieldName' first input parameter this value should be a match with our 'name' attribute value on the form file input field. So our interceptor read our files that are attached to the file input field. Another input parameter of 'MulterOptions' that provides configuration like file destination path, customizing file name, etc. FilesInterceptor: The 'FilesInterceptor' will be decorated on t