With the launch of .NET Core 3.0 and Visual Studio 16.3.0, support for creating web apps using the Blazor template is now natively enabled. This makes it easy for you to run your C# libraries directly in the browser.
Enabling WebAssembly in Visual Studio
To begin developing client-side Blazor projects in Visual Studio, you will need to install the WebAssembly template from the command line. A new Blazor WebAssembly preview launched in conjunction with the .NET Core 3.0 release. To install the latest preview, execute the following command via the Package Manager Console in Visual Studio. The command can also be run from a cmd or PowerShell terminal window.
dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.0.0-preview9.19465.2
With the WebAssembly template installed, you can now create a client-side Blazor project. Start by creating a new Blazor App project.
After choosing a name for your project, you will have the option to select a server-side or WebAssembly (client-side) Blazor project. Select Blazor WebAssembly App to create your first client-side Blazor project.
In the Solution Explorer, right-click your project and select Add > New Item…. Add a new Razor Component item. Name the component
The Razor syntax is a combination of HTML and C# that can be used to create beautiful and functional web apps. Begin by providing a heading, some instructional information, and a button for your new Blazor app.
In Razor, the
@ symbol indicates that C# code will follow instead of HTML. A C# event handler, then, can be assigned to a button’s
onclick event or a form’s
onsubmit event by prepending
@ to the attribute’s name, or example
@onsubmit. The following code will show you how to assign a C# method named
WriteToConsole() to the
onclick event of the button you just created.
<button class="btn btn-primary" @onclick="WriteToConsole">Click me</button>
With Razor, it is simple to define C# methods to use within your page by including them inside a
@code block at the bottom of the Razor Component file.
To test your
WriteConsole.razor Razor Component, add it as an element to the project’s
@page "/" <WriteConsole />
The Bottom Line
Console.WriteLine() in the same way that
Don't stop learning!
There is so much to discover about C#. That's why I am making my favorite tips and tricks available for free. Enter your email address below to become a better .NET developer.
Before we go
Your support of my open-source work will help me continue to provide free tutorials and tips for people like you.