Skip to footer content
.NET HELP

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

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 UIs 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 reuse 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 allow 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;

    // This method increments the counter value when the button is clicked
    private void IncrementCount()
    {
        currentCount++;
    }
}

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 - PDF Generation for .NET. It's easy to use, includes many features, and is free for development. You can learn more about using IronPDF in your Blazor App by reading the IronPDF Blazor Documentation.

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; }

    // This method calls the service to generate a PDF document from a given URL
    protected async Task GeneratePDF()
    {
        await ForecastService.GeneratePDFfromURL(URL);
    }
}

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.Threading.Tasks;
using IronPdf;

namespace myBlazorAPP.Data
{
    public class WeatherForecastService
    {
        // This method generates a PDF file asynchronously from a provided URL
        public async Task GeneratePDFfromURL(string URL)
        {
            ChromePdfRenderer renderer = new ChromePdfRenderer();
            var pdfDoc = await renderer.RenderUrlAsPdfAsync(URL);
            pdfDoc.SaveAs(@"myFile.pdf");
        }
    }
}
using System;
using System.Threading.Tasks;
using IronPdf;

namespace myBlazorAPP.Data
{
    public class WeatherForecastService
    {
        // This method generates a PDF file asynchronously from a provided URL
        public async Task GeneratePDFfromURL(string URL)
        {
            ChromePdfRenderer renderer = new ChromePdfRenderer();
            var pdfDoc = await renderer.RenderUrlAsPdfAsync(URL);
            pdfDoc.SaveAs(@"myFile.pdf");
        }
    }
}
Imports System
Imports System.Threading.Tasks
Imports IronPdf

Namespace myBlazorAPP.Data
	Public Class WeatherForecastService
		' This method generates a PDF file asynchronously from a provided URL
		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
$vbLabelText   $csharpLabel

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 Software's Iron Suite Products. You can save money and purchase five products for the cost of purchasing two of them by acquiring the full Iron Suite.

Summary

Blazor is a framework for building interactive client-side web UI with Microsoft's .NET Framework.

  • Create rich interactive UIs 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.

Frequently Asked Questions

What is Blazor Framework?

Blazor is an ASP.NET Framework launched by Microsoft in 2018 that allows developers to create Single Page Web Applications using C# instead of JavaScript.

How does Blazor WebAssembly work?

Blazor WebAssembly is a Single-Page App (SPA) framework that runs .NET code in web browsers using WebAssembly, allowing for interactive client-side web apps without the need for plugins.

What is WebAssembly?

WebAssembly is a compact bytecode format optimized for fast download and execution that enables running .NET code inside web browsers. It is supported by all modern browsers.

What is Blazor Hybrid?

Blazor Hybrid allows developers to build native client apps using Blazor components across mobile, desktop, and web platforms. It utilizes .NET MAUI for cross-platform applications.

How do you create a Blazor Server Application in Visual Studio?

To create a Blazor Server Application, open Visual Studio, create a new project, select the Blazor Server App Template, name the project, select a target framework, and then create the project.

How can Blazor components be reused?

Blazor components are defined in .razor files and can be reused across different parts of an application to build interactive and modular web UIs.

What is the role of JavaScript Interoperability in Blazor?

JavaScript Interoperability, or JS interop, allows WebAssembly code to access the full functionality of the browser via JavaScript, enabling .NET code to run effectively in the browser's sandbox environment.

How can you generate a PDF from a URL in a web application?

To generate a PDF from a URL in a web application, you can use IronPDF, a library for PDF generation in .NET. It allows you to create PDFs using the ChromePdfRenderer class.

What are the advantages of using Blazor for web development?

Blazor allows developers to write client-side web applications in C#, share logic between server and client, leverage .NET libraries, and benefit from .NET's performance, reliability, and security.

How does Blazor integrate with hosting platforms?

Blazor integrates with modern hosting platforms, such as Docker, enabling the deployment of applications on various server environments with ease.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.
Talk to an Expert Five Star Trust Score Rating

Ready to Get Started?

Nuget Passed