Introduction
Microsoft has recently announced the release of a new .NET web framework – Blazor. In this article, we will understand Blazor and setup Blazor development environment in our machine. We will also execute our first program in ASP.NET core using Blazor and Visual Studio 2017. We will create a sample calculator application using Blazor.
What is Blazor?
Blazor is a new .NET web framework for creating client-side applications using C#/Razor and HTML. Blazor runs in the browser with the help of WebAssembly. It can simplify the process of creating single page application (SPA). It also provides a full stack web development experience using .NET.
Using .NET for developing Client-side application has multiple advantages as mentioned below,
- .NET offers a range of API and tools across all platform that are stable and easy to use.
- The modern languages such as C# and F# offer a lot of features that make programming easier and interesting for developers.
- The availability of one of the best IDE in form of Visual Studio provides a great .NET development experience across multiple platforms such as Windows, Linux, and MacOS.
- .NET provides features such as speed, performance, security, scalability, and reliability in web development that makes full stack development easier.
What is WebAssembly?
WebAssembly is developed as a web standard and is supported by all the major browsers without plugins.
Why should we use Blazor?
Blazor supports features of a SPA framework such as:
- Routing
- Layouts
- Forms and validation
- JavaScript interop
- Build on save
- Server-side rendering
- Dependency Injection
Prerequisites
The Blazor is not supported on versions below Visual Studio 2017 v15.7
Source Code
The source code has been updated to .NET Core 3.2 Preview-1. Get the source code from Github
Getting Started with Blazor
To create our first Blazor application we need to install “ASP.NET Core Blazor Language Services extension” from here.
Install this extension and it will be added to your VS 2017.
Open Visual Studio and select File >> New >> Project. After selecting the project, a “New Project” dialog will open. Select .NET Core inside Visual C# menu from the left panel. Select “ASP.NET Core Web Application” from available project types. Put the name of the project as BlazorDemo
and press OK.
Create a Sample Calculator Using Blazor
We are going to create a basic calculator app. This calculator will perform addition, subtraction, multiplication, and division operations. Right click on Pages folder and select Add >> New Item. An “Add New Item” dialog box will open. Select Web from the left panel, select “Razor View” from templates panel. Put the name as Calculator.cshtml
. Press OK.
Calculator.cshtml
and put the following code into it.@page "/calculator" <h1>Basic Calculator Demo Using Blazor</h1> <hr /> <div> <div class="row"> <div class="col-sm-3"> <p>First Number</p> </div> <div class="col-sm-4"> <input placeholder="Enter First Number" bind="@num1" /> </div> </div> <br /> <div class="row"> <div class="col-sm-3"> <p>Second Number</p> </div> <div class="col-sm-4"> <input placeholder="Enter Second Number" bind="@num2" /> </div> </div> <br /> <div class="row"> <div class="col-sm-3"> <p>Result</p> </div> <div class="col-sm-4"> <input readonly bind="@finalresult" /> </div> </div> <br /> <div class="row"> <div class="col-sm-2"> <button onclick="@AddNumbers" class="btn">Add (+)</button> </div> <div class="col-sm-2"> <button onclick="@SubtractNumbers" class="btn btn-primary">Subtract (−)</button> </div> <div class="col-sm-2"> <button onclick="@MultiplyNumbers" class="btn btn-success ">Multiply (X)</button> </div> <div class="col-sm-2"> <button onclick="@DivideNumbers" class="btn btn-info">Divide (X)</button> </div> </div> </div> @functions { string num1; string num2; string finalresult; void AddNumbers() { finalresult = (Convert.ToDouble(num1) + Convert.ToDouble(num2)).ToString(); } void SubtractNumbers() { finalresult = (Convert.ToDouble(num1) - Convert.ToDouble(num2)).ToString(); } void MultiplyNumbers() { finalresult = (Convert.ToDouble(num1) * Convert.ToDouble(num2)).ToString(); } void DivideNumbers() { if (Convert.ToDouble(num2) != 0) { finalresult = (Convert.ToDouble(num1) / Convert.ToDouble(num2)).ToString(); } else { finalresult = "Cannot Divide by Zero"; } } }
Let’s understand this code. On the top, we are defining the route of this page using @page
directive. So in this application, if we append “/calculator” to base URL, we will be redirected to this page.
We have defined the HTML section to read two numbers from the user and display the result in another textbox. The attribute “bind” is used to bind the value entered in the textbox to the variables we have defined. We also created four buttons to perform our basic arithmetic operations. We are calling our business logic methods on button click.
@functions
section which contains all our business logic. We have declared three variables, two to read the value from the user and another one to display the result. We have defined four methods to handle addition, subtraction, multiplication, and division. The “bind” attribute will work only for string variables not for floating point values. Hence, we need to convert a string to double to perform our arithmetic operations.Finally, we will add the link to our “calculator” page in the navigation menu, open /Shared/NavMenu.cshtml
page and put the following code into it.
<div class="top-row pl-4 navbar navbar-dark"> <a class="navbar-brand" href="/">BlazorTest</a> <button class="navbar-toggler" onclick=@ToggleNavMenu> <span class="navbar-toggler-icon"></span> </button> </div> <div class=@(collapseNavMenu ? "collapse" : null) onclick=@ToggleNavMenu> <ul class="nav flex-column"> <li class="nav-item px-3"> <NavLink class="nav-link" href="/" Match=NavLinkMatch.All> <span class="oi oi-home" aria-hidden="true"></span> Home </NavLink> </li> <li class="nav-item px-3"> <NavLink class="nav-link" href="/counter"> <span class="oi oi-plus" aria-hidden="true"></span> Counter </NavLink> </li> <li class="nav-item px-3"> <NavLink class="nav-link" href="/fetchdata"> <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data </NavLink> </li> <li class="nav-item px-3"> <NavLink class="nav-link" href="/calculator"> <span lass="oi oi-list-rich" aria-hidden="true"></span> Calculator </NavLink> </li> </ul> </div> @functions { bool collapseNavMenu = true; void ToggleNavMenu() { collapseNavMenu = !collapseNavMenu; } }
Congrats! We have created our first application using ASP.NET Core and Blazor. Let’s execute the code and see the output.
Execution Demo
Launch the application. You can see a “Calculator” link in the navigation menu on the left. Click on it to navigate to our calculator page. Notice the URL, it has /calculator
appended to it.
Let’s perform add operation. Input two numbers and click on Add(+) button. You can see the addition result in the Result textbox.
Now try to perform division on two numbers. You can get the result in Result textbox. If you try to perform division by Zero, you will get an error message “Cannot Divide by Zero”.
Similarly, try other operations and see the result.
Conclusion
We learned about the new .NET framework – Blazor. We have also created a simple calculator application using Blazor and perform arithmetic operations on it.
Try this new framework and let me know what you think of it in the comments section below.
Get my book Blazor Quick Start Guide to learn more about Blazor.
You can also find this article at C# Corner.
You can check my other articles on ASP .NET Core here
See Also
- ASP.NET Core – CRUD Using Angular 5 And Entity Framework Core
- CRUD Operations With ASP.NET Core Using Angular 5 and ADO.NET
- Getting Started With Angular 5 Using Visual Studio Code
- CRUD Operation With ASP.NET Core MVC Using Visual Studio Code and EF
- CRUD Operation With ASP.NET Core MVC Using ADO.NET and Visual Studio 2017
- CRUD Operation With ASP.NET Core MVC using Visual Studio Code and ADO.NET
Very nice tutorial
Thanks
Hi Ankit,
I read this nice article and also tried my self. I have installed VS 2019 preview community edition for learning purpose.
I write my code as well as tried your one, but I got the following error message in both
“Cannot convert method group ‘AddNumbers’ to non-delegate type ‘object’. Did you intend to invoke the method?
VS give me this error on every method, even on his own function “@IncrementCount”.
Please advice the suitable solution.
Thanks & Best Regards
There are some breaking changes in the latest version of Blazor. This can be the reason for this error. You can see the list of changes at https://devblogs.microsoft.com/aspnet/asp-net-core-and-blazor-updates-in-net-core-3-0-preview-6/. Update your code accordingly and see if the issue is resolved. If the issue persists, post it on SO. If someone has faced the similar problem they will reply to it.
Thanks for the prompt reply.
after reading the link mentioned by you, I just changed calculator.cshtml to calculator.razor and calculator is working fine now.
regards
Thanks for the great article sir!
But the extension https://marketplace.visualstudio.com/items?itemName=aspnet.blazor won’t install in my VS2017 (Enterprise). However when installed using CLI it works:
“dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.0.0-preview6.19307.2”
Still the templates won’t display on the New Project. You must use the CLI to create a new Blazor project:
“dotnet new blazorserverside”
or “dotnet new blazorhosted”
or “dotnet new blazorlib”
or “dotnet new blazor”
The project won’t build or run in the VS2017 IDE. Again, you must use the CLI:
“dotnet build”
“dotnet run”
The latest version of Blazor is based .NET Core 3 which is only supported in VS 19.