.NET HELP

What is Blazor Framework (How it Works for Developers Tutorial)

Published January 31, 2023
Share:

Blazor is an ASP.NET Framework launched by Microsoft back in 2018. The launch of the Blazor framework was advantageous as it allowed developers to create Single Page Web Applications using C# instead of JavaScript.

Blazor lets you build interactive web UI's using C# that runs in the browser with WebAssembly (abbreviated as Wasm). Blazor apps are composed of reusable web UI components implemented using C#, HTML, and CSS. Both client and server code is written in C#, allowing you to share code and libraries.

Blazor can run your client-side C# code directly in the browser using WebAssembly. Because it's .NET running on WebAssembly, you can re-use code and libraries from server-side parts of your application.

Alternatively, Blazor can run your client logic on the server. Client UI events are sent back to the server using SignalR, a real-time messaging framework. Once execution completes, the required UI changes are sent to the client and merged into the Document Object Model (DOM).

What is WebAssembly?

Blazor WebAssembly is a Single-Page App (SPA) framework for building interactive client-side web apps with .NET. Blazor WebAssembly uses open web standards that allows development without plugins or recompiling code into other languages. Blazor WebAssembly works in all modern web browsers.

Running .NET code inside web browsers is made possible by WebAssembly. WebAssembly is a compact bytecode format optimized for fast download and maximum execution speeds. WebAssembly is an open web standard and is supported in web browsers without plugins.

WebAssembly code can access the full functionality of the browser via JavaScript. Known as JavaScript Interoperability, it is often shortened to JavaScript interop or JS interop. .NET code executed via WebAssembly runs in the browser's JavaScript sandbox with the protections that the sandbox provides against malicious actions on the client machine.

Build Native Apps

We can build native client apps using existing Blazor Web UI components with Blazor Hybrid. Blazor components can be shared across mobile, desktop, and web while taking advantage of full access to native client capabilities. We can use Blazor Hybrid to build cross-platform apps with .NET Multi-platform App UI (MAUI), or to modernize existing Windows Presentation Foundation (WPF) and Windows Forms apps.

In a Blazor Hybrid app, Razor components run natively on the device. Components render to an embedded Web View control through a local interop channel. Components don't run in the browser, and WebAssembly isn't involved. Razor components load and execute code quickly, and components have full access to the native capabilities of the device through the .NET platform.

Let's create a demo application to better understand how Blazor apps work.

Create a Blazor Server Application

To create our first Blazor app, we need to create a new Visual Studio project.

  • Open Visual Studio.
  • Click on the Create New Project button.
  • Select Blazor Server App Template.
  • Click on the Next button.
  • Name your Application.
  • Click on the Next button.
  • Select a target Framework.
  • Click on the Create Project button.

A New Project will be created as shown below.

What is Blazor and How Does It Work - Figure 1

Several files were created to give you a simple Blazor app that is ready to run.

  • Program.cs is the entry point for the app that starts the server and where you configure the app services and middleware.
  • App.razor is the root component of the app.
  • The Pages directory contains some example web pages for the app.
  • The launchSettings.json file inside the Properties directory defines different profile settings for the local development environment. A port number is automatically assigned at project creation and saved to this file.

Run this template app.

Running the Blazor App

There are three Blazor components automatically created in the template.

Home Component

What is Blazor and How Does It Work - Figure 2

Click on Counter on the side menu. You will see that clicking the button increments the counter without changing or reloading the page. Incrementing the counter dynamically in a web application normally requires JavaScript, but with Blazor, we can achieve this using C#. This is the reason that ASP.NET developers like Blazor so much. It helps .NET developers build web apps quickly and easily.

Counter Component

What is Blazor and How Does It Work - Figure 3

We can see the code of the Counter component in the Counter.razor file located inside the Pages folder of our solution.

@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++;
    }
}
@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++;
    }
}
Friend page "/counter" (Of h1) Counter</h1> (Of p) Current count
	Inherits currentCount</p> <button class="btn btn-primary" onclick="IncrementCount"> Click [me]</button> code

	Private currentCount As Integer = 0

	Private Sub IncrementCount()
		currentCount += 1
	End Sub
End Class
VB   C#

A request for /counter in the browser, as specified by the @page directive at the top, causes the Counter component to render its content.

Each time the Click me button is selected:

  • The onclick event is executed.
  • The IncrementCount method is called.
  • The currentCount is incremented.
  • The component is rendered to show the updated count.

Each of the .razor files defines a UI component that can be reused.

Open the Index.razor file in Visual Studio. The Index.razor file already exists because it was created when you created the project. It's located in the Pages folder inside the BlazorApp directory that was created earlier.

Fetch Component

There is another component named "Fetch Component". This component also injects a service used for backend server-side development. Let's replace this code to generate a PDF from a URL to better understand the power of Blazor web development.

Generate PDF from URL

First of all, we need to install a third-party library for generating PDF files. The library we will use is IronPDF. It's easy to use, includes many features, and is free for development. You can learn more about using IronPDF in your Blazor App from reading the Blazor Tutorial.

Install IronPDF NuGet Package

We can also install the IronPDF NuGet package in the Blazor WebAssembly app similar to the normal ASP.NET Core application.

Open NuGet Package Manager Console, and write the following command:

Install-Package IronPdf

The library will be installed as shown below.

What is Blazor and How Does It Work - Figure 4

Remove all the existing code from FetchData.razor file and add the following code sample:

@page "/fetchdata"

@using myBlazorAPP.Data
@inject WeatherForecastService ForecastService

<h1>Generate PDF FROM URL</h1>
<p>This component demonstrates generating PDF from URL using IronPDF in Blazor Application</p>
<input type="text" @bind="URL" placeholder="URL HERE..."/>
<button @onclick="generatePDF" > Generate PDF </button>

@code {

    private string URL { get; set; }
    protected async Task generatePDF()
    {
        await ForecastService.GeneratePDFfromURL(URL);
    }
}
@page "/fetchdata"

@using myBlazorAPP.Data
@inject WeatherForecastService ForecastService

<h1>Generate PDF FROM URL</h1>
<p>This component demonstrates generating PDF from URL using IronPDF in Blazor Application</p>
<input type="text" @bind="URL" placeholder="URL HERE..."/>
<button @onclick="generatePDF" > Generate PDF </button>

@code {

    private string URL { get; set; }
    protected async Task generatePDF()
    {
        await ForecastService.GeneratePDFfromURL(URL);
    }
}
'INSTANT VB TODO TASK: The following line could not be converted:
page "/fetchdata" [using] myBlazorAPP.Data inject WeatherForecastService ForecastService (Of h1) Generate PDF FROM URL</h1> (Of p) This component demonstrates generating PDF from URL using IronPDF in Blazor Application</p> <input type="text" bind="URL" placeholder="URL HERE..."/> <button onclick="generatePDF" > Generate PDF </button> code
If True Then

	private String URL {get;set;}
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	protected async Task generatePDF()
'	{
'		await ForecastService.GeneratePDFfromURL(URL);
'	}
End If
VB   C#

Above is the client-side Blazor code for generating PDF files. It defines one button and one input box. The input field is bound to the URL variable.

Now, let's write server-side code for our app.

Open WeatherForecastService.cs file and replace all the existing code with the following code snippet:

using System;
using System.Linq;
using System.Threading.Tasks;
using IronPdf;

namespace myBlazorAPP.Data
{
    public class WeatherForecastService
    {
        public async Task GeneratePDFfromURL (string URL)
        {
            ChromePdfRenderer renderer = new ChromePdfRenderer();
            var pdfDOc = await renderer.RenderUrlAsPdfAsync(URL);
            pdfDOc.SaveAs(@"myFile.pdf");
        }
    }
}
using System;
using System.Linq;
using System.Threading.Tasks;
using IronPdf;

namespace myBlazorAPP.Data
{
    public class WeatherForecastService
    {
        public async Task GeneratePDFfromURL (string URL)
        {
            ChromePdfRenderer renderer = new ChromePdfRenderer();
            var pdfDOc = await renderer.RenderUrlAsPdfAsync(URL);
            pdfDOc.SaveAs(@"myFile.pdf");
        }
    }
}
Imports System
Imports System.Linq
Imports System.Threading.Tasks
Imports IronPdf

Namespace myBlazorAPP.Data
	Public Class WeatherForecastService
		Public Async Function GeneratePDFfromURL(ByVal URL As String) As Task
			Dim renderer As New ChromePdfRenderer()
			Dim pdfDOc = Await renderer.RenderUrlAsPdfAsync(URL)
			pdfDOc.SaveAs("myFile.pdf")
		End Function
	End Class
End Namespace
VB   C#

Let's run our application to see the output.

What is Blazor and How Does It Work - Figure 5

Paste a URL in the input box and click on Generate PDF. The PDF file will be generated and the file can be seen in the app folder.

Open the PDF file as shown below.

What is Blazor and How Does It Work - Figure 6

We have generated a PDF from the URL with just three lines of code. This is the power of IronPDF.

IronPDF is provided by Iron Software and it is part of Iron Suite. You can save money and purchase five products for the cost of purchasing two of them by purchasing the complete Iron Suite.

Summary

Blazor is a framework for building interactive client-side web UI with .NET

  • Create rich interactive UI's using C# instead of JavaScript.
  • Share server-side and client-side app logic written in .NET.
  • Render the UI as HTML and CSS for wide browser support, including mobile browsers.
  • Integrate with modern hosting platforms, such as Docker.
  • Build hybrid desktop and mobile apps with .NET and Blazor.

Using .NET for client-side web development offers the following advantages:

  • Write code in C# instead of JavaScript.
  • Leverage the existing .NET ecosystem of .NET libraries.
  • Share app logic across server and client.
  • Benefit from .NET's performance, reliability, and security.
  • Stay productive on Windows, Linux, or macOS with a development environment, such as Visual Studio or Visual Studio Code.
  • Build on a common set of languages, frameworks, and tools that are stable, feature-rich, and easy to use.
< PREVIOUS
.NET MAUI Blazor for (PDF,EXCEL,OCR,BARCODE,QR Code)
NEXT >
Razor vs Blazor

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >