Begin with Blazor(SPA web app with C# Code)

Begin with Blazor(SPA web app with C# Code)

Introduction to Blazor

Microsoft has recently announced the release of a new .NET web framework, Blazor. Blazor is a free, open source Web framework to build Web apps using C# that run in a Web browser. In this article, we will understand Blazor and setup Blazor development environment in our machine and execute our first program in ASP.NET core using Blazor and Visual Studio 2019. We will also create a sample calculator application using Blazor.

What is Blazor ?

Before getting start introduction of blazor we must have knowledge of WebAssembly(wasm). The WebAssembly(wasm) is a specification for the browser which is introduced

in 2015 and it defines as a compressed binary code arrangement designed as a portable target for compilation on the web for server and client applications.

After this release, many companies have launched projects with a high-level programming language to run on the top of WebAssembaly. The team Microsoft has a take the initiative to start its Blazor project and now we can use Blazor to run c# in a front end web app. this is happening due to WebAssembly open standard specification, the .Net code can run on the browser without the use of any plugins.

The Blazor is good for single page application frontend development which uses c# as a full-stack. We can write frontend app code with c# without depending on javascript as we would typically with React, jQuery, or Angular because Blazor will take the place of all of that. connect with Asp.Net Core server code it’s mean we can now have .Net as an end to end

The Blazor components are written as C# classes, then built into .NET assemblies. Which responsible for output and input operations handle user event and render the UI. Components also work as a container that is shared, distributed, reused, across multiple apps.

The HTML page that had a JavaScript function to perform frontend logic is simple to the frontend developer. The Blazor component is declared as a markup file .razor extension contains the HTML elements with the c# code responsible for event handling and HTML rendering.

Why 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 have 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 a SPA framework such as:

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

Prerequisites

  • Install .NET Core 3.1 SDK
  • Install latest preview of Visual Studio 2019 from here

Getting Started with Blazor

Open Visual Studio >> Create New Project. After selecting the project, a "New Project" dialog will open. Select Blazor App C# menu from the right panel. Then, select “Blazor Server App” from available project types. Put the name of the project as BlazorSample and press OK.

No alt text provided for this image
No alt text provided for this image

Now, our first Blazor project will be created. You can observe the folder structure in Solution Explorer as shown in the below image.

No alt text provided for this image

You can see that we have a “Pages” folder. We will be adding our view pages to this folder only and these pages will be rendered on the web. Execute the program, it will be open the browser and you will see a page similar to the one shown below.

No alt text provided for this image

Create a Sample Calculator Using Blazor

 We are going to create a basic calculator app, which is able to do addition, subtraction, multiplication, and division. Right click on Pages folder and select Add Razor Component dialog box will open. Then select “Razor Component” from templates panel and put the name as Calculator.razor. Press OK.

No alt text provided for this image

Open 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-md-3">
            <p>First Number</p>
        </div>
        <div class="col-md-4">
            <input placeholder="Enter First Number" @bind="@num1" />
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-md-3">
            <p>Second Number</p>
        </div>
        <div class="col-md-4">
            <input placeholder="Enter Second Number" @bind="@num2" />
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-md-3">
            <p>Result</p>
        </div>
        <div class="col-md-4">
            <input readonly @bind="@finalresult" />
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-md-2">
            <button @onclick="AddNumbers" class="btn btn-light">Add (+)</button>
        </div>
        <div class="col-md-2">
            <button @onclick="SubtractNumbers" class="btn btn-primary">Subtract (−)</button>
        </div>
        <div class="col-md-2">
            <button @onclick="MultiplyNumbers" class="btn btn-success ">Multiply (X)</button>
        </div>
        <div class="col-md-2">
            <button @onclick="DivideNumbers" class="btn btn-info">Divide (/)</button>
        </div>
    </div>
</div>


@code { 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 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 our business logic methods on button click.

 At the bottom of the page, we have a @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 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.cshtml page and put the following code into it.

<div class="top-row pl-4 navbar navbar-dark">
    <a class="navbar-brand" href="">BlazorSample</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 lass="oi oi-list-rich" 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;
    }
}

 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.

No alt text provided for this image
Moral of the story
 We learned about the new .NET framework – Blazor. We have also created a simple calculator application using Blazor and performed arithmetic operations on it. Please refer to the attached source code for better understanding.
 You can also fork this application on Github. Try this new framework and let me know what you think of it in the comments section below.

To view or add a comment, sign in

More articles by Ravinder Singh

Others also viewed

Explore content categories