Blazor Web Framework in C#
Blazor Web Framework in C#
27 July 2020
Blazor is a new technology developed by Microsoft. If you are familiar with client-side technologies, think of it as C# on the client-side. Instead of using JavaScript on the front-end to power up your web applications now we can use Blazor on the front end. By using Blazor we can run C# code as a front end.
Using Blazor on the client-side will provide the benefits of .NET’s performance, reliability and security. Also using Visual Studio will be efficient on Windows, Linux as well as macOS. Building applications with common languages, tools and frameworks will be another added benefit. Blazor uses components as UI elements which can be page, dialog.
Client-Side Blazor
Client-side Blazor (Blazor WebAssembly) provides full support for Progressive Web apps. It can be run offline. Client-side Blazor is a single page app framework to build the client-side web apps using .NET. Through WebAssembly, the client-side version will run in the browser and DOM updates will be done there. Running Blazor WebAssembly app in browser will compile C# code razor files into .NET assemblies. Blazor WebAssembly does not require the Use of .NET on the server-side. It can be used to build static sites.
Server-Side Blazor
Using SignalR pipeline the server-side blazor will retain the model of DOM and transmits the diffs back and forth to the client-side. The server will process the logic and transmit the result back to the client. Whole code will be executed on the server and only UI updates will be exchanged with the client. It doesn’t allow offline mode.
Counter.Razor
@page "/counter" <h1>Counter</h1> <p>Current Count: @currentCount</p> <button class="btn btn-primary" onClick="IncrementCount">Click me</button> @code { int currentCount = 0; void incrementCount() { currentCount++; } }
In the above code snippet, the @code section is fully C# code. The @code section contains the properties and methods which are created as part of the component class. The @currentCount binds to the related property of the component. The button element shows how to bind to JavaScript events. As we are prefixing the event with @ results in evaluating the target as C# method instead of JavaScript.