14. ASP.NET CORE 5 : Blazor Getting Started : Calculator module

Ankit Sharma, 2020.05.28 Updated to .NET Core 3.2 Preview-1

Tutorial: https://www.c-sharpcorner.com/article/getting-started-with-blazor/

Github: https://github.com/AnkitSharma-007/ASPCore.BlazorDemo

Calculator module using Blazor

Prerequisites
  • Install .NET Core  SDK from here  or SDK preview
  • Install Visual Studio Community 2019  Latest with the ASP.NET and web development workload selected from here or preview
  • Entity Framework Core Tools >> NuGet or on command-line tools: dotnet tool install –global dotnet-ef
    (Install ASP.NET Core Blazor Language Services extension from here not needed (needed in VS2019) older ?))
  • SQL Server 2012 or above

STEP 1. 

  1. VS2019 >> File >> New >> Project
  2. Select Blazor App C# (older : .NET Core inside Visual C# menu from the left panel)
  3. Select Blazor App (older : “ASP.NET Core Web Application”) from available project types.
  4. Put the name of the project as BlazorDemoCalc and J:\netcore\source\repos
  5. Click “Blazor WebAssembly App”, “ASP.NET Core hosted”, “Progressive web app”

 

STEP 2. Client proj, Pages folder. We will be adding our view pages to this folder only. These pages will be rendered on the web.

Execute the program – displays navigation links Home, Counter, Fetch data in navigation menu are displayed.

  1. Right click on Pages folder in Client proj >> select Add >> New Item
  2.  “Add New Item” dialog box will open. Selected is Visual C# from the left panel (old : select Web) ,
  3. select Razor Component from templates panel and put the name as Calculator (old : Razor View – empty)

J:\netcore\source\repos\BlazorDemoCalc\BlazorDemo\Pages\Calculator.razor

@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 Calculator.razor

On the top, we are defining the route of this page using @page directive. So in this module, 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 @code (was functions) section which contains all our business logic. We have declared three variables, two variables 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.

 

 

STEP 3.  Add the link to our “calculator” page in the navigation menu, open /Shared/NavMenu.razor page

J:\netcore\source\repos\BlazorDemoCalc\BlazorDemo\Shared\NavMenu.razor

and put the following BLUE COLORED code into it.

<div class="top-row pl-4 navbar navbar-dark">
    <a class="navbar-brand" href="">BlazorDemoCalcDev</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-plus" 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;
    }
}

 

What is Blazor

Blazor framework is not supported by versions below Visual Studio 2017 v15.7. Microsoft defined Blazor as an experimental project and it was in alpha phase as of March 30, 2018. Blazor is new free, open source .NET Web framework for creating client-side applications using C# / Razor and HTML that runs in the browser with WebAssembly, see http://webassembly.org/

What is WebAssembly

WebAssembly (abbreviated Wasm) is low-level assembly-like language with a compact binary format that can run in modern web browser. Since it is a low-level binary code, it cannot be read/written by humans but we can compile the code from other languages to WebAssembly to facilitate their execution on the browser. It is a subset of JavaScript and is designed to complement and run alongside JavaScript. It enables us to run code written in multiple language on the web at near native speed.
WebAssembly is developed as a web standard and is supported by all the major browsers without plugins.

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

Using .NET for developing Client-side application has multiple advantages :

  1. .NET offers a range of API and tools across all platform that are stable and easy to use.
  2. The modern languages such as C# and F# offer a lot of features that make programming easier and interesting for developers.
  3. 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.
  4. .NET provides features such as speed, performance, security, scalability, and reliability in web development that makes full stack development easier.

 

 

See Fluxor https://github.com/mrpmorris/fluxor

https://medium.com/pipelinespace/setting-up-a-ci-cd-pipeline-in-azure-devops-for-blazor-and-deploy-to-azure-c262c58d8172

 

Leave a Reply

Your email address will not be published. Required fields are marked *

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