Free Web Development Online Tutorials, Learn to Code
What is Blazor in Asp.net Core, blazor application tutorial, blazor database query

What is Blazor in Asp.net Core?

Blazor is the new framework from Microsoft for building lightweight interactive client-side web UI with .NET, now we can build rich interactive UIs using C# instead of JavaScript, All functions we used to write in JavaScript client side, now can be written in C#, what else you want! This Blazor tutorial will cover everything from scratch.

Blazor Tutorial in Asp.net Core

You must have ASP.NET Core 3.1 and above installed in your machine to develop Blazor application.

So, if you have visual studio 2019 installed in your machine, then you have ready environment to develop blazor project.

You also can manually install the Blazor WebAssembly template by executing the following command

dotnet new -i Microsoft.AspNetCore.Components.WebAssembly.Templates::3.2.0-preview2.20160.5

Or, open your Nuget package manager, and look for Microsoft.AspNetCore.Components.WebAssembly.Templates template.

So, just start your Visual Studio , look for blazor in search box, select the blazor template and click next.

Once you create the Blazor project, you will see the following ready to use sample project, in this project you will get example of how blazor code works.

Here is an example of how easily you can write client side function in C# just like you used to write in JavaScript.

@code {
    private int currentCount = 0;
    private void IncrementCount()
    {
        currentCount++;
    }
}

You can write C# code just like JavaScript code within @code {} block and then call the function from button click, Calling a function in button click @onclick="IncrementCount"

@page "/counter"
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
    private int currentCount = 0;
    private void IncrementCount()
    {
        currentCount++;
    }
}

Create Razor Page

To create a new razor page, you just need to add a page with .razor extension in “pages” folder, then the page must have @page directive and then the page name like example below

@page "/students"

Note: the physical page name, and the name you specify at page directive, can be different; the name you specify at page directive will be served in browser as page name. This is the place where you can define SEO friendly page name, for example the default @page "/fetchdata" you can specify as @page "/weather-report-today” so in browser when you access the page, you access as “weather-report-today”, which may look more meaningful.

To access any service in the page, you need to inject the reference as example below.

@inject WeatherForecastService ForecastService
@inject DataAccessService DaService

You can add any assembly reference like below.

@using BlazorAppWTR.Data
@using BlazorAppWTR.BO

Database access from Blazor page

Now we see how to access data from MS-SQL database in Blazor application

In this exercise, you will learn how to read values from Blazor app setting values from appsetting.json, though I posted earlier how to read from appsetting.json, but here we read values straight from appsetting to our service using IConfiguration dependency injection.

appsettings.json in blazor app

I have added a new section called “DbConfig” in my appsettings.json, with all database related information like database name, username, password server name etc.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "DbConfig": {
    "DatabaseName": "MyDatabaseName",
    "UserName": "myusername",
    "Password": "mypassword",
    "ServerName": "ACMachine\\SQLEXPRESS"
  },
  "AllowedHosts": "*"
}

Data Access Service in Blazor App

Now, we have to create a database access service class, where we read all database related information from appsettings and form a database connection string, notice, in following “DataAccessService” class we are reading configuration information using IConfiguration instance created in constructor.

public class DataAccessService
{
    private   IConfiguration config;
    public  DataAccessService(IConfiguration configuration)
    {
        config = configuration;
    }

    private  string ConnectionString
    {
        get
        {
    string _server = config.GetValue<string>("DbConfig:ServerName");
    string _database = config.GetValue<string>("DbConfig:DatabaseName");
    string _username = config.GetValue<string>("DbConfig:UserName");
    string _password = config.GetValue<string>("DbConfig:Password");

    return ($"Server={_server};Database={_database};User ID={_username};Password={_password};Trusted_Connection=False;MultipleActiveResultSets=true;");
        }
    }
  }

Here we have one GetStudents method Task<List<Student>> GetStudents() to get the student list from database.

Note: Here I have used ado.net SqlDataAdapter to read data from database; you can use entity framework or any other mechanism to retrieve data from database, but make sure finally you return an async result set.

using BlazorAppWTR.BO;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace BlazorAppWTR.Data
{
    public class DataAccessService
    {
        private   IConfiguration config;
        public  DataAccessService(IConfiguration configuration)
        {
            config = configuration;
        }

        private  string ConnectionString
        {
            get
            {
                string _server = config.GetValue<string>("DbConfig:ServerName");
                string _database = config.GetValue<string>("DbConfig:DatabaseName");
                string _username = config.GetValue<string>("DbConfig:UserName");
                string _password = config.GetValue<string>("DbConfig:Password");
                return ($"Server={_server};Database={_database};User ID={_username};Password={_password};Trusted_Connection=False;MultipleActiveResultSets=true;");
            }
        }
		

        public async Task<List<Student>> GetStudents()
        {
            List<Student> students = new List<Student>();
            Student s;
            DataTable dt = new DataTable();
            SqlConnection con = new SqlConnection(ConnectionString);
            SqlDataAdapter da = new SqlDataAdapter("select * from [dbo].[tbStudent]", con);
            da.Fill(dt);
            foreach (DataRow row in dt.Rows)
            {
                s = new Student();
                s.StuId = Convert.ToInt32(row["StuId"]);
                s.FirstName = row["Firstname"] as string;
                s.LastName = row["Lastname"] as string;
                s.Email = row["Email"] as string;
                s.Mobile = row["ContactNumber"] as string;
                students.Add(s);
            }
            return await Task.FromResult(students);
        }
         
    }
}

Register service in Startup.cs

Like any other .net core application, we need to register all services in startup file.

So, now we register the DataAccessService class in ConfigureServices method of startup.cs file like demonstrated below.

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

Display data in Razor Page

Now let’s see how to call the data access service from razor page.

You can load data into a private variable on OnInitializedAsync method.

@code {
    private List<Student> students;

    protected override async Task OnInitializedAsync()
    {
        students = await DaService.GetStudents();
    }
}

In razor view we can now check if the local variable value is empty, if not display all student details by looping through the property.

@page "/students"
@using BlazorAppWTR.Data
@using BlazorAppWTR.BO
@inject DataAccessService DaService


<h1>Students</h1>

@if (students == null)
{
    <div>There is no student added</div>
}
else
{
    foreach (Student s in students)
    { 
        <div style="padding:15px;border-bottom:solid 1px #0094ff;">
            @s.FirstName @s.LastName | @s.Email
        </div>
    }
}

@code {
private List<Student> students;
    protected override async Task OnInitializedAsync()
    {
        students = await DaService.GetStudents();
    }
}

Hope this will help you to get started with Blazor application development

Comment
Name
Email
Website
Subscribe
 
Blazor in Asp.net Core
ASP.NET MVC Interview Questions Answers


Asp.Net Core C# Examples | Join Asp.Net MVC Course