Learn about Blazor. Harness the potential of .NET and C# to build web applications without JavaScript.

Marcin Sulecki
Calendar icon
26 czerwca 2023

In recent years, we have seen web applications supplant the "old-school" desktop by becoming the standard. To provide the same speed and convenience of web applications, the processing of user interaction had to be moved from the server to the browser. Hence, frameworks such as ASP.NET Core MVC or Razor Pages, which were so popular among .NET developers until recently, became insufficient.

Instead, Angular, React and Vue environments have become popular, but a barrier for C# developers is the need to use JavaScript in them. Partially this problem is solved by TypeScript, but it still requires learning a new language, which increases the time to master the technology.

The ideal solution from the point of view of a .NET programmer would be to be able to use C# on both the client and server side.

And this is where Blazor comes onto the scene

What is Blazor?

Blazor is an open source framework created by Microsoft for creating interactive web applications using pure C#, HTML code and Razor templates instead of JavaScript. Creating the solution involves defining components from which we build pages, which we then use inside the application. What's more, we can still use our favorite libraries in C#, which makes application development much easier.

While browsers can't directly run code in C#, they do support the WebAssembly format, which is the foundation for Blazor.

How does it work?

WebAssembly, or WASM for short, can most easily be imagined as a binary library that a browser downloads along with an HTML page and executes its code in an isolated environment, in a so-called "sandbox." WASM is currently supported by all popular browsers, as can be seen at https://caniuse.com/wasm. Under the hood, WASM is a low-level programming language with a textual representation in the form of S-expression notation.

Example:

1(module (import "env" "memory" (memory 1)) (import "env" "log" (func $log (param i32 i32))) (data (i32.const 0) "Hello, World!") (func (export "hello") i32.const 0 i32.const 13 call $log ) ) )

The above code prints the text "Hello World!" to the browser console.

But where is the promised C# code? C#, like many other programming languages, can be compiled into WASM and run directly in the browser or alternatively on the server side depending on the hosting model you choose. The entire compilation process is taken care of by Blazor so the .NET developer can focus on the C# code of the application.

Application development

To start the adventure with Blazor, knowledge of C#, basic HTML and CSS is required.

If you have experience with MVC and Razor Pages then you will certainly benefit from it, because many mechanisms are carried over alive into Blazor, such as Razor syntax, Tag Helpers and attributes.

In Blazor, everything is a component, from page layout (Layout) to pages (Pages) and controls. So your job will be to compose, that is, to combine individual components into a whole.

Let's look at the code for a sample page:

1@page "/customers/{name}" @using Microsoft.AspNetCore.Authorization; @inject HttpClient Http @attribute [Authorize] <PageTitle>Hello @customer.Name</PageTitle> @if (@customer is null) { <LoadingComponent>Loading data...</LoadingComponent> } else { <p>Welcome: @customer.Name</p> } <button class="btn btn-primary" @onclick="GetCustomer">Get Customer</button> @code { private Customer? customer; [Parameter] public string Name { get; set; } private async Task GetCustomer() { customer = await Http.GetAsync($"/api/customers/{Name}"); } }

At the top is a section with tags common to the entire page:

  • @page indicates that this is a page, available at the indicated address (known as routing)
  • @using attaches the indicated namespace
  • @inject allows dependencies to be injected directly into the page
  • @attribute is used to declare attributes, in this case authorization is required
  • in turn gives us control over the page title

The next section is responsible for the view, which we define using HTML and Razor syntax to bind data (data-binding) and handle events. You can use conditional statements and loops in it, and you don't have to worry about refreshing the view-Blazor applies changes to the DOM automatically. We can also embed predefined components.

In the @code section we place the logic of the page, i.e. variables and methods, which we write in C#. For better readability, we can move this code to a separate file (partial class).

Remember that Blazor is not just a library, but an entire framework rich in many useful mechanisms:

  • Routing allows you to navigate between components in your application without reloading the entire application
  • Dependency injection provides injection of registered services
  • Cascading parameters simplify passing information to nested components
  • Isolated CSS streamlines application styling
  • Form validation facilitates verification of entered data
  • JavaScript Interop allows you to call JavaScript functions from C# and vice versa
  • Debugger provides essentialdebugging tools

Developing applications in Blazor is really fun, and Microsoft is making more improvements from version to version to make it even easier and faster.

Where is Blazor used?

Blazor is suitable for creating both simple SPA applications in the style of a tax calculator as well as complex projects, such as workflow management.

The key issue before starting the project is to choose the Blazor Server or Blazor WebAssembly hosting model. The advantage of the first approach is that such an application can be launched immediately, but it is required to constantly maintain a connection to the server. The second approach allows connectionless applications to be created, but the disadvantage is increased startup time.

This is expected to improve, according to the announcement, because with the release of .NET 8 will come another model, Blazor Unified, which will combine both approaches into one. The programmer will already be able to decide at the component level which side the code should execute on, or enable an automatic mode that will make that decision on its own.

Microsoft points to one more use of Blazor for developing mobile and desktop applications. This involves placing Blazor components inside a native application in the MAUI.NET environment As a result, a single code can be shared by a web, mobile and desktop application which for some may be a key issue when choosing a technology.

Summary

Many say that the future of web applications will belong to WebAssembly. So Blazor fits perfectly into this trend, offering .NET developers a convenient tool for building modern solutions. So it is not worth waiting, but start learning about the new technology now, because in a moment it may become a key technology in the .NET ecosystem.

If you want to get to know Blazor inside out, check out the Creating Applications in Blazor 7.0 training, during which we will create a complete solution with database access and authorization. See you there!

Read also

Calendar icon

28 marzec

RABATKA Action - Discover the spring promotion!

The annual spring promotion is underway: RABATKA Action, thanks to which you can save on open training from our proprietary offer.

Calendar icon

8 marzec

Don’t miss the opportunity - register for the IREB exploRE 2024 conference and meet the best experts in the field of requirements

We invite you to the IREB exploRE 2024 conference dedicated to requirements engineering and business analysis. The conference will ta...

Calendar icon

18 styczeń

How to prepare for the ISTQB® Foundation Level exam?

How toprepare for the ISTQB® Foundation Level exam? Check valuable tips before taking the test.