Blazor comes with the following features:
- Run C# code inside your browser as WebAssembly (WASM)
- Blazor is a mix of browser and Razor
- Messages between the browser and the backend are sent via SignalR
- Modern browser support WASM: Firefox, Chrome, Edge, Safari (IE 11 does not)
- Components can be shared via Nuget
There are two different versions: Blazor Server and Blazor Webassembly. I will talk about the difference in more detail in my next post. For now, you only have to remember that the Server version runs on the server and sends code to the browser and the Webassembly version runs directly in the browser and calls APIs, like Angular or React apps.
Create your First Blazor Server App
To follow the demo you need Visual Studio 2019 and at least .NET Core 3.0. You can find the source of the demo on Github.
To create a new Blazor App, select the Blazor template in Visual Studio.
After entering a name and location, select Blazor Server App, and click on Create.
This creates the solution and also a demo application. Start the application and you will see a welcome screen and a menu on the left side. Click on Fetch data to see some information about the weather forecast or on Counter to see a button which increases the amount when you click it.
Create a new Component
Open the Counter.razor file in the Pages folder and you can see the whole code for the implementation of the Counter feature.
On the top, you have the page attribute which indicates the route. In this example, when you enter /counter, this page will be rendered. The logic of the functionality is in the code block and the button has an onclick event. This event calls the IncrementCount method which then increases the count of the currentCode variable.
Create a new Page
In this section, I will add a new Blazor component with a dropdown menu, event handling, and binding of a variable.
Right-click on the Pages folder and add a Blazor Component with the name DisplayProducts. Then add the following code:
This code sets the route to products and displays a headline. In the code block, I override the OnInitialized method and create a class Product. The OnInitialized method is executed during the load of the page. You might know this from Webforms. Next, I add a dropdown menu and add each element of my Products list.
As the last step, I add an onchange event to the dropdown menu and the code of the executed method in the code block. The selected value will be displayed below the dropdown menu. If you haven’t selected anything, the whole div tag won’t be displayed. My whole component looks like the following:
Run the application, navigate to /products and you will see the dropdown menu. Select a product and it will be displayed below the dropdown.
You can find the source of the demo on Github.