Getting started with Blazor using ASP.NET Core 3.1

Getting started with blazor

Blazor is a free and open-source web framework developed by Microsoft. With Blazor we can create web apps using C# and HTML that can run on client side (browser) and also on server side.

Advantages of Blazor

  • .NET Ecosystem
  • C# (LINQ and asynchronous programming)
  • Sharing code between front end and back end
  • Working with components

There are two hosting models available for building .net blazor

  1. Blazor WebAssembly
  2. Blazor Server-Side

Why we should use Blazor

Blazor makes web development easier and more productive by providing a full stack web development with .NET. It runs in all browsers on the real .NET runtime and has full support for .NET standard without the need of any extra plugin. Blazor is fast, have reusable components and is open source with a great support from the community.

Blazor also supports features of SPA framework such as:

  • Routing
  • Layouts
  • Forms and validation
  • JavaScript interop
  • Build on save
  • Server-side rendering
  • Dependency injection

Prerequisites

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.1.0-preview4.19579.2

Creating our First Blazor App

Open visual studio 2019 and select “create a new project”

Select the Project type you wanna create. In our case “Blazor app” and click Next

On the next screen give the project name, location and solution name. We will give the project name as Blazor Demo and click create.

Next window will ask you to select the Blazor template. We will select Blazor WebAssembly as we don’t require Blazor server side for this app. Finally click on create button.


After creating you get a demo project to get started. You can observe the folder structure in Solution Explorer as shown in the below image.

You can see that we have a “Pages” folder where we will be adding our view pages to this folder only and these pages will be rendered on the web. When you run the project you see a page similar to the one shown below.

Here you can see a navigation menu on the left side, which contains the navigation links to all the pages we have in our application. By default, we have “Counter” and “Fetch Data” pages provided. We are going to add a “Calculator” page for our sample calculator application.

Creating Simple Calculator App Using Blazor

We are going to create a simple calculator app, which is able to do addition, subtraction, multiplication, and division. Right click on Pages folder and select Add >> New Item. An “Add New Item” dialog box will open. Select Razor Component and give the name as Calculator.razor and click add.

Open calculator.razor and put the following code into it.


@page  "/calculator"

<h3>Simple Calculator Demo using Blazor</h3>
<hr />
<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>

<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>

<div class="row">
    <div class="col-sm-3">
        <p>Result</p>
    </div>
    <div class="col-sm-4">
        <input placeholder="Enter Second Number" @bind="result" />
    </div>
</div>

<div class="row">
    <div class="col-sm-2">
        <button @onclick="Add" class="btn btn-primary">Add (+)</button>
    </div>

    <div class="col-sm-2">
        <button @onclick="Subtract" class="btn btn-primary">Subtract (-)</button>
    </div>

    <div class="col-sm-2">
        <button @onclick="Multiply" class="btn btn-primary">Multiply (X)</button>
    </div>

    <div class="col-sm-2">
        <button @onclick="Divide" class="btn btn-primary">Divide (/)</button>
    </div>
</div>

@code {

    private string num1 = string.Empty;
    private string num2 = string.Empty;
    private string result;

    void Add()
    {
        result = (Convert.ToDouble(num1) + Convert.ToDouble(num2)).ToString();
    }

    void Subtract()
    {
        result = (Convert.ToDouble(num1) - Convert.ToDouble(num2)).ToString();
    }

    void Multiply()
    {
        result = (Convert.ToDouble(num1) * Convert.ToDouble(num2)).ToString();
    }

    void Divide()
    {
        if(Convert.ToDouble(num2) != 0)
        {
            result = (Convert.ToDouble(num1) / Convert.ToDouble(num2)).ToString();
        }
        else
        {
            result = "Cannot Divide by Zero";
        }
    }
}

Let’s understand the code. On the top, we are defining the route of this page @page directive. So in this application, if we append “/calculator” to base URL then we will be redirected to this page.

Then 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 functions on button click.

At the bottom of the page, we have a @code section which contains all the logic. We have declared three variables, two to read the value from the user and another one to display the result. We have also 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.razor page and put the following code into it.

<div class="top-row pl-4 navbar navbar-dark">
    <a class="navbar-brand" href="">BlazorDemo</a>
    <button class="navbar-toggler" @onclick="ToggleNavMenu">
        <span class="navbar-toggler-icon"></span>
    </button>
</div>

<div class="@NavMenuCssClass" @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 class="oi oi-tablet" aria-hidden="true"></span> Calculator
            </NavLink>
        </li>
    </ul>
</div>

@code {
    private bool collapseNavMenu = true;

    private string NavMenuCssClass => collapseNavMenu ? "collapse" : null;

    private void ToggleNavMenu()
    {
        collapseNavMenu = !collapseNavMenu;
    }
}

Congratulations! We have created our first application using ASP.NET Core 3.1 and Blazor. Let’s execute the code and see the output.

Executing Demo

Launch the application. You can see a “Calculator” link in the navigation menu on the left. Click on it to navigate to calculator page. Notice the URL, it has /calculator appended to it.

Let’s perform addition. Input two numbers and click Add (+) button. You can see the result in the result text box.

Similarly you can try other operations and check the result.

Conclusion

We learn about the new .NET framework – Blazor using asp.net core 3.1. We also created a simple calculator application using blazor and perform mathematical operations on it.

Try out the demo blazor application and let me know what you think of it in the comment section below.

Get Free Email Updates!

Signup now and receive an email once I publish new content.

I agree to have my personal information transfered to MailChimp ( more information )

I will never give away, trade or sell your email address. You can unsubscribe at any time.

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of