Are you looking for the Blazor tutorial? If you do, then you have come to the right place!

Blazor is a framework that is built by the ASP.NET team to enable developers to build client-side web applications using .NET.

It also allows the developers to use C# for core programming and Razor for building interactive user interfaces for the web.

  1. Blazor Basic Models
  2. Blazor Server Application Creation
  3. Model and Service Creation
  4. Creating Razor Components
  5. Running Blazor Server Application

Getting Started with Blazor

So, if you are a .NET developer, then you can always benefit from learning Blazor. In this tutorial, we will learn how to create a simple quiz manager.

So, let’s get started.

Blazor Basic Models

Blazor offers the developers two way to create web applications:

  • Blazor Server Hosting Model
  • Blazor WebAssembly

Pre-requisites

To get started, you need to have .NET Core 3.0 SDK installed on your system. To check if you have it installed on your system, run the following command in the terminal window.

dotnet –version

Blazor Tutorial
Caption: Dotnet version 3.0.103 installed

If not installed, then you can need to download it from here.

Blazor Server Application Creation

Now we need to start our Blazor server application. To get started, type the following command in the terminal window.

dotnet new blazorserver -o QuizApp

Once done successfully, the server will be created.

Blazor Programming Tutorial
Caption: The server is ready to use

The command is useful as it generates the project template. As you can see, it has created a project folder QuizApp and within, it will create other key folders including the following

  • Data → The data folder is where the services and models are implemented
  • Pages → The pages folder is used to store HTML views
  • Shared → The shared folder is where the Razor components and other elements are stored.
Learn Blazor
Caption: QuizApp project folder contents

Model and Service Creation

With our basic template ready, we now need to create our first file which we name as QuizList.cs file. However, before you create it, you need to delete everything within the data folder.

Now, copy-paste the following code in the QuizList.cs file.

// Data/QuizList.cs

using System;
using System.Collections.Generic;

namespace QuizApp.Data
{
    public class QuizList
    {
        public string Question { get; set; }
        public List<string> Choices { get; set; }
        public int AnswerIndex { get; set; }
        public int Score { get; set; }

        public QuizList()
        {
            Choices = new List<string>();
        }
    }
}

The code simply does class implements the items within the quiz. As you can see we create question string variables, its choices, answer index, and the score.

Next, we need to create a new file in the data folder. Let’s name it QuizServe.cs

Here we will create a class that defines the QuizList instances which will be initialized by the QuizServe() constructor.

// Data/QuizServe.cs

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace QuizApp.Data
{
    public class QuizServe
    {
        private static readonly List<QuizList> Quiz;

        static QuizServe()
        {
            Quiz = new List<QuizList> {
                new QuizList
                {
                    Question = "Which is the most basic programming language that Microsoft ever created?",
                    Choices = new List<string> {"Visual Basic", "Batch", "C++", "DirectX", ".NET namespace"},
                    AnswerIndex = 1,
                    Score = 1
                },
                new QuizList
                {
                    Question = "The most popular language by Microsoft is",
                    Choices = new List<string> {"C#", "Visual Basic"},
                    AnswerIndex = 0,
                    Score = 2
                }
            };
        }

        public Task<List<QuizList>> GetQuizAsync()
        {
            return Task.FromResult(Quiz);
        }
    }
}

Lastly, we need to create another file named Startup.cs. This file needs to be created at the root of your project and is used to define ConfigureServices().

// Startup.cs

using System;
// Other using clauses
namespace QuizApp
{
    public class Startup
    {
        //no changes here

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddSingleton<QuizService>();
        }

      //no changes here
    }
}

Creating Razor Components

To create the UI, we need to use Razor as a template processor. It will create dynamic HTML containing markup self-contained units.

First, we need to remove the default sample project files within the Pages folder. For this, we remove two files including FetchData.razor and Counter.razor.

After removing them, create a new file named, QuizView.razor

Here, you need to copy-paste the following code.

// Pages/QuizView.razor

 @page "/quizView"

 @using QuizApp.Data
 @inject QuizService QuizRepository

<h1>Let's start with the quiz</h1>
<p>Your current score is @currentScore</p>

@if (quiz == null)
{
    <p><em>Starting Quiz....</em></p>
}
else
{
    int quizIndex = 0;
    @foreach (var QuizList in quiz)
    {
        <section>
            <h3>@QuizList.Question</h3>
            <div class="form-check">
            @{
                int choiceIndex = 0;
                quizScores.Add(0);
            }
            @foreach (var choice in QuizList.Choices)
            {
                int currentQuizIndex = quizIndex;
                <input class="form-check-input" type="radio" name="@quizIndex" 
value="@choiceIndex" @onchange="@((eventArgs) => 
UpdateScore(Convert.ToInt32(eventArgs.Value), currentQuizIndex))"/>@choice<br>

                choiceIndex++;
            }
            </div>
        </section>

        quizIndex++;
    }
}

@code {
    List<QuizList> quiz;
    List<int> quizScores = new List<int>();
    int currentScore = 0;

    protected override async Task OnInitializedAsync()
    {
        quiz = await QuizRepository.GetQuizAsync();
    }

    void UpdateScore(int chosenAnswerIndex, int quizIndex)
    {
        var QuizList = quiz[quizIndex];

        if (chosenAnswerIndex == QuizList.AnswerIndex)
        {
            quizScores[quizIndex] = QuizList.Score;
        } else
        {
            quizScores[quizIndex] = 0;
        }
        currentScore = quizScores.Sum();
    }
}

In the above code, we render the UI. Most of the code is self-explanatory. Also, the main thing that is making all of these to happen is the @page directive and properly setting up the routing settings.

Next, we replace the content of NavMenu.razor with the following code.

// Shared/NavMenu.razor
<div class="top-row pl-4 navbar navbar-dark">
   <a class="navbar-brand" href="">QuizApp</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="quizViewer">
              <span class="oi oi-list-rich" aria-hidden="true"></span> Quiz
           </NavLink>
       </li>
   </ul>
 </div>

@code {
   bool collapseNavMenu = true;
   string NavMenuCssClass => collapseNavMenu ? "collapse" : null;

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

Running Blazor Server Application

To run the application, you need to type the following in the terminal.

dotnet run

If everything runs, you should be able to access your application at the following URL.

https://localhost:5001

Congratulations! You have successfully created your first Blazor app. From here, you can expand the basic structure to more complex features.

So, what are you going to make? Comment below and let us know!