Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

ASP.NET Core and Getting Started With Blazor

DZone's Guide to

ASP.NET Core and Getting Started With Blazor

Are you a huge .NET fan? Read on to learn about .NET's latest framework, Blazor, and how to you can use it to build web applications.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Microsoft has recently announced the release of a new .NET web framework - Blazor. In this article, we will check out Blazor and set up a Blazor development environment on our machine and execute our first program in ASP.NET Core using Blazor and Visual Studio 2017. We will also 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 that runs in the browser with WebAssembly. It can simplify the process of creating single page applications (SPAs) and at the same time enables full stack web development using .NET.

Using .NET for developing client-side applications has multiple advantages that are mentioned below:

  1. .NET offers a range of APIs and tools across all platforms that are stable and easy to use.
  2. Modern languages such as C# and F# offer a lot of features that make programming easier and more interesting for developers.
  3. Visual Studio provides a great .NET development experience across multiple platforms (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.

Microsoft defined Blazor as an experimental project and since it is still in the alpha phase (as of March 30, 2018) so, it should not be used in a production environment.

Prerequisites

  • Install .NET Core 2.1 Preview 1 SDK from here.
  • Install latest preview of Visual Studio 2017 (15.7) from here.

Blazor is not supported by Visual Studio versions below Visual Studio 2017, v15.7

Source Code

Before proceeding, I would recommend you to get the source code from GitHub.

Getting Started With Blazor

To create our first Blazor application, we need to install the “ASP.NET Core Blazor Language Services extension” from here.

Install this extension and add it 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 the Visual C# menu from the left-hand panel. Then, select “ASP.NET Core Web Application” from available project types. Set the name of the project as  BlazorDemo and press OK.

After clicking on OK, a new dialog will open asking you to select the project template. You can observe two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.0” from these dropdowns. Then, select “Blazor” template and press OK.

Now, our first Blazor project will be created. You can observe the folder structure in Solution Explorer as shown in the below 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.

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 >> New Item. An “Add New Item” dialog box will open. Select Web from the left-hand panel, then select “Razor View” from templates panel and set the name as Calculator.cshtml. Then press OK.

 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-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. At the top, we are defining the route of this page using the @page directive. So in this application, if we append "/calculator" to the 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 when a button is clicked.

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='main-nav'>  
    <div class='navbar navbar-inverse'>  
        <div class='navbar-header'>  
            <button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'>  
                <span class='sr-only'>Toggle navigation</span>  
                <span class='icon-bar'></span>  
                <span class='icon-bar'></span>  
                <span class='icon-bar'></span>  
            </button>  
            <a class='navbar-brand' href='/'>BlazorDemo</a>  
        </div>  
        <div class='clearfix'></div>  
        <div class='navbar-collapse collapse'>  
            <ul class='nav navbar-nav'>  
                <li>  
                    <NavLink href="/" Match=NavLinkMatch.All>  
                        <span class='glyphicon glyphicon-home'></span> Home  
                    </NavLink>  
                </li>  
                <li>    
                    <NavLink href="/counter">  
                        <span class='glyphicon glyphicon-education'></span> Counter  
                    </NavLink>  
                </li>  
                <li>  
                    <NavLink href="/fetchdata">  
                        <span class='glyphicon glyphicon-th-list'></span> Fetch data  
                    </NavLink>  
                </li>  
                <li>  
                    <NavLink href="/calculator">  
                        <span class='glyphicon glyphicon-th-list'></span> Calculator  
                    </NavLink>  
                </li>  
            </ul>  
        </div>  
    </div>  
</div>

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 an add operation. Input two numbers and click on the  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 the 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 performed arithmetic operations on it.

Try this new framework and let me know what you think of it in the comments section below.

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
web dev ,asp.net ,blazor ,web application development

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}