Skip to main content

Single Page Application Using Server-Side Blazor

Introduction

In this article, we will create a Single Page Application (SPA) using the server-side Blazor concepts with the help of Entity Framework Core database first approach. Single-Page Applications are web applications that load a single HTML page and dynamically update that page as the user interacts with the app.

We will be creating a sample Employee Record Management System and perform CRUD operations on it. A modal popup will display the form to handle the use inputs and the form also have a dropdown list, which will bind to a database table. We will also provide a filter option to the user to filter the employee records based on employee name.

We will be using Visual Studio 2017 and SQL Server 2017 for our demo.

Let us look at the final application

What is Server-Side Blazor?

The release 0.5.0 of Blazor allows us to run Blazor applications on the server. This means that we can run Blazor component server-side on .NET Core while other functionalities such as UI updates, event handling, and JavaScript interop calls are handled by a SignalR connection over the network.

For more information, refer to my previous article on Understanding Server-Side Blazor.

Prerequisites

  • Install the .NET Core 2.1 or above SDK from here
  • Install Visual Studio 2017 v15.7 or above from here
  • Install ASP.NET Core Blazor Language Services extension from here
  • SQL Server 2012 or above.

Visual Studio 2017 versions below v15.7 does not support Blazor framework.

Source Code

Get the source code for this application from GitHub.

Creating Table

We will be using two tables to store our data.

  1. Employee: – Used to store the details of employee. It contains fields such as EmployeeID, Name, City, Department, and Gender.
  2. Cities: – This contains the list of cities and used to populate the City field of Employee table. It contains two fields CityID and CityName

Execute the following commands to create both tables.

CREATE TABLE Employee (  
EmployeeID int IDENTITY(1,1) PRIMARY KEY,  
Name varchar(20) NOT NULL ,  
City varchar(20) NOT NULL ,  
Department varchar(20) NOT NULL ,  
Gender varchar(6) NOT NULL  
)    
GO      
      
CREATE TABLE Cities (      
CityID int IDENTITY(1,1) NOT NULL PRIMARY KEY,      
CityName varchar(20) NOT NULL       
)      
GO 

Now, we will put some data into the Cities table. We will be using this table to bind a dropdown list in our web application from which the user will select the desired city. Use the following insert statements.

INSERT INTO Cities VALUES('New Delhi');  
INSERT INTO Cities VALUES('Mumbai');  
INSERT INTO Cities VALUES('Hyderabad');  
INSERT INTO Cities VALUES('Chennai');  
INSERT INTO Cities VALUES('Bengaluru');

Now, our Database part is complete. Therefore, we will proceed to create the server side application using Visual Studio 2017.

Create Server Side Blazor Application

Open Visual Studio and select File >> New >> Project.

After selecting the project, a “New Project” dialog will open. Select .NET Core inside Visual C# menu from the left panel. Then, select “ASP.NET Core Web Application” from available project types. Put the name of the project as ServerSideSPA 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.1” from these dropdowns. Then, select “Blazor (Server-side in ASP.NET Core)” template and press OK

This will create our server-side Blazor solution. You can observe the folder structure in solution explorer, as shown in the below image,

The solution has two project files,

  1. ServerSideSPA.App: This is our server side Blazor app. This project has all our component logic and our services. We will also create our models and data access layer in this project.
  2. ServerSideSPA.Server: This is the ASP.NET Core hosted application. Instead of running client-side in browser the server side Blazor app run in the ASP.NET Core host application.

In future release of Blazor these two projects might be merged into one, but for now the separation is required due to the differences in the Blazor compilation model.

Scaffolding the Model to the Application

We are using Entity Framework core database first approach to create our models. We will create our model class in ServerSideSPA.App project.
Navigate to Tools >> NuGet Package Manager >> Package Manager Console. Select ServerSideSPA.App from Default project drop-down. Refer to image below,

First, we will install the package for the database provider that we are targeting which is SQL Server in this case. Hence, run the following command,

Install-Package Microsoft.EntityFrameworkCore.SqlServer

Since we are using Entity Framework Tools to create a model from the existing database, we will install the tools package as well. Hence, run the following command, 

Install-Package Microsoft.EntityFrameworkCore.Tools

After you have installed both the packages, we will scaffold our model from the database tables using the following command,

Scaffold-DbContext "Your connection string here" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables Employee, Cities

Do not forget to put your own connection string (inside ” “). After this command gets executed successfully you can observe a Models folder has been created inside ServerSideSPA.App project and it contains three class files myTestDBContext.cs, Cities.cs and Employee.cs. The name of your DB Context class will be the name of your database suffixed with the word Context. Here my database name is myTestDB, hence the context class name is myTestDBContext. Hence, we have successfully scaffolded our Models using EF core database first approach.

Creating Data Access Layer for the Application

Right-click on ServerSideSPA.App project and then select Add >> New Folder and name the folder as DataAccess. We will be adding our class to handle database related operations inside this folder only.

Right click on DataAccess folder and select Add >> Class.

Name your class EmployeeDataAccessLayer.csOpen EmployeeDataAccessLayer.csand put the following code into it,

using Microsoft.EntityFrameworkCore;
using ServerSideSPA.App.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ServerSideSPA.App.DataAccess
{
    public class EmployeeDataAccessLayer
    {
        myTestDBContext db = new myTestDBContext();

        //To Get all employees details     
        public List<Employee> GetAllEmployees()
        {
            try
            {
                return db.Employee.AsNoTracking().ToList();
            }
            catch
            {
                throw;
            }
        }

        //To Add new employee record       
        public void AddEmployee(Employee employee)
        {
            try
            {
                db.Employee.Add(employee);
                db.SaveChanges();
            }
            catch
            {
                throw;
            }
        }

        //To Update the records of a particluar employee      
        public void UpdateEmployee(Employee employee)
        {
            try
            {
                db.Entry(employee).State = EntityState.Modified;
                db.SaveChanges();
            }
            catch
            {
                throw;
            }
        }

        //Get the details of a particular employee      
        public Employee GetEmployeeData(int id)
        {
            try
            {
                var employee = db.Employee.Find(id);
                db.Entry(employee).State = EntityState.Detached;
                return employee;
            }
            catch
            {
                throw;
            }
        }

        //To Delete the record of a particular employee      
        public void DeleteEmployee(int id)
        {
            try
            {
                Employee emp = db.Employee.Find(id);
                db.Employee.Remove(emp);
                db.SaveChanges();
            }
            catch
            {
                throw;
            }
        }

        // To get the list of Cities
        public List<Cities> GetCityData()
        {
            try
            {
                return db.Cities.ToList();
            }
            catch
            {
                throw;
            }
        }
    }
}

Here, we have defined the methods to handle database operations. GetAllEmployees will fetch all the employee data from Employee table. Similarly, AddEmployee will create a new employee record and UpdateEmployee will update the record of an existing employee. GetEmployeeData will fetch the record of the employee corresponding to the employee ID passed to it and DeleteEmployee will delete the employee record corresponding to the employee id passed to it. GetCityData will fetch the list of all the cities from Cities table.

Creating the Service class

Right click on Services folder and select Add >> Class. Give the name of class as EmployeeService.cs and click Add. This will add the EmployeeService class to the Services folder.

Open EmployeeService.cs and put the following code into it,

using ServerSideSPA.App.DataAccess;
using ServerSideSPA.App.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ServerSideSPA.App.Services
{
    public class EmployeeService
    {
        EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();

        public Task<List<Employee>> GetEmployeeList()
        {
            return Task.FromResult(objemployee.GetAllEmployees());
        }

        public void Create(Employee employee)
        {
            objemployee.AddEmployee(employee);
        }
        public Task<Employee> Details(int id)
        {
            return Task.FromResult(objemployee.GetEmployeeData(id));
        }

        public void Edit(Employee employee)
        {
            objemployee.UpdateEmployee(employee);
        }
        public void Delete(int id)
        {
            objemployee.DeleteEmployee(id);
        }
        public Task<List<Cities>> GetCities()
        {
            return Task.FromResult(objemployee.GetCityData());
        }
    }
}

We will invoke the methods of EmployeeDataAccessLayer class from our service. The service will be injected to our components and the components will call the service methods to access the database.

At this point of time the ServerSideSPA.App project has the following structure:

Configuring the Service

To make the service available to the components we need to configure it on the server side app. Open ServerSideSPA.App >> Startup.cs file. Add the following line inside the ConfigureServices method of Startup class.

services.AddSingleton<EmployeeService>();

Refer to the image below:

Now we will proceed to create our view component.

Creating the View Component

We will add the Razor page in ServerSideSPA.App /Pages folder. By default, we have “Counter” and “Fetch Data” pages provided in our application. These default pages will not affect our application but for the sake of this tutorial, we will delete fetchdata and counter pages from ServerSideSPA.App /Pages folder.

Right-click on ServerSideSPA.App /Pages folder and then select Add >> New Item. An “Add New Item” dialog box will open, select “ASP.NET Core” from the left panel, then select “Razor Page” from templates panel and name it EmployeeData.cshtml. Click Add.

This will add an EmployeeData.cshtml page to the Pages folder. This razor page will have two files, EmployeeData.cshtmland EmployeeData.cshtml.cs.
Now, we will add codes to these pages.

EmployeeData.cshtml

Open EmployeeData.cshtml page and put the following code into it.

@page "/fetchemployee"
@inherits EmployeeDataModel

<h1>Employee Data</h1>
<p>This component demonstrates CRUD operation on Employee data</p>

<div>
    <div style="float:left">
        <button class="btn btn-primary" onclick="@AddEmp">Add Employee</button>
    </div>
    <div style="float:right; width:40%;">
        <div class="col-sm-6" style="float:left">
            <input class="form-control" type="text" placeholder="Search" bind="@SearchString" />
        </div>
        <div>
            <button type="submit" class="btn btn-default btn-info" onclick="@FilterEmp">Filter</button>
        </div>
    </div>
</div>

@if (empList == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class='table'>
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Gender</th>
                <th>Department</th>
                <th>City</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var emp in empList)
            {
                <tr>
                    <td>@emp.EmployeeId</td>
                    <td>@emp.Name</td>
                    <td>@emp.Gender</td>
                    <td>@emp.Department</td>
                    <td>@emp.City</td>
                    <td>
                        <button class="btn btn-default" onclick="@(async () => await EditEmployee(@emp.EmployeeId))">Edit</button>
                        <button class="btn btn-danger" onclick="@(async () => await DeleteConfirm(@emp.EmployeeId))">Delete</button>
                    </td>
                </tr>
            }
        </tbody>
    </table>

    if (isAdd)
    {
        <div class="modal" tabindex="-1" style="display:block" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title">@modalTitle</h3>
                        <button type="button" class="close" onclick="@closeModal">
                            <span aria-hidden="true">X</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="form-group">
                                <label for="Name" class="control-label">Name</label>
                                <input for="Name" class="form-control" bind="@emp.Name" />
                            </div>
                            <div class="form-group">
                                <label asp-for="Gender" class="control-label">Gender</label>
                                <select asp-for="Gender" class="form-control" bind="@emp.Gender">
                                    <option value="">-- Select Gender --</option>
                                    <option value="Male">Male</option>
                                    <option value="Female">Female</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label asp-for="Department" class="control-label">Department</label>
                                <input asp-for="Department" class="form-control" bind="@emp.Department" />
                            </div>
                            <div class="form-group">
                                <label asp-for="City" class="control-label">City</label>
                                <select asp-for="City" class="form-control" bind="@emp.City">
                                    <option value="">-- Select City --</option>
                                    @foreach (var city in cityList)
                                    {
                                        <option value="@city.CityName">@city.CityName</option>
                                    }
                                </select>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-block btn-info" onclick="@(async () => await SaveEmployee())" data-dismiss="modal">Save</button>
                    </div>
                </div>
            </div>
        </div>
    }

    if (isDelete)
    {
        <div class="modal" tabindex="-1" style="display:block" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title">Delete Employee</h3>
                    </div>
                    <div class="modal-body">
                        <h4>Do you want to delete this employee ??</h4>
                        <table class="table">
                            <tr>
                                <td>Name</td>
                                <td>@emp.Name</td>
                            </tr>
                            <tr>
                                <td>Gender</td>
                                <td>@emp.Gender</td>
                            </tr>
                            <tr>
                                <td>Department</td>
                                <td>@emp.Department</td>
                            </tr>
                            <tr>
                                <td>City</td>
                                <td>@emp.City</td>
                            </tr>
                        </table>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-danger" onclick="@(async () => await DeleteEmployee(emp.EmployeeId))" data-dismiss="modal">YES</button>
                        <button class="btn btn-warning" onclick="@closeModal">NO</button>
                    </div>
                </div>
            </div>
        </div>
    }
}

Let us understand this code. At the top we have defined the route of this page as “/fetchemployee”. This means if we append “/fetchemployee” to the root URL of the app, we will be redirected to this page.

We are also inheriting EmployeeDataModel class, which is defined in EmployeeData.cshtml.cs file. This will allow us to use the methods defined in EmployeeDataModel class.

After this, we have defined a button to add new employee record. When clicked, this button will open a modal popup to handle the user inputs.

We have also defined a searchbox and corresponding button to filter the employee records based on employee name. If you enter an employee name and click on filter button, it will show all the employee record for which the name matches the value entered in the field. If we click on filter button without entering any value in the search box, it will return all the employee records.

The employee records returned from the database is stored in the empList variable. If the variable is not null then we will bind the values to a table to display the employee records in tabular fashion. Each employee record will also have two action links, Edit to edit the employee record and Delete to delete the employee record. 

To handle the user inputs we are using a form. We are using a single form for both Add Employee and Edit Employee functionality. The form is defined in a modal popup and the modal popup is displayed on the screen based on the value of a Boolean property isAdd. The value of this Boolean property is set in the code behind (.cshtml.cs) page.

The City dropdown list inside the form is binding to our Cities table in database with the help of cityList variable. The cityList will be populated as the application boots up.

The form will have a Save button which will invoke SaveEmployee method, defined in the code behind file to Add or update an employee record.

Similar to Add modal popup, we also have a Delete modal popup. It will be a read only modal and ask for a confirmation to delete an employee record. Upon clicking “Yes”, it will invoke the DeleteEmployee method to delete the employee record.

EmployeeData.cshtml.cs

Open EmployeeData.cshtml.cs and put the following code into it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Blazor;
using Microsoft.AspNetCore.Blazor.Components;
using Microsoft.AspNetCore.Blazor.Services;
using ServerSideSPA.App.Models;
using ServerSideSPA.App.Services;

namespace ServerSideSPA.App.Pages
{
    public class EmployeeDataModel : BlazorComponent
    {
        [Inject]
        protected EmployeeService employeeService { get; set; }

        protected List<Employee> empList;
        protected List<Cities> cityList = new List<Cities>();
        protected Employee emp = new Employee();
        protected string modalTitle { get; set; }
        protected Boolean isDelete = false;
        protected Boolean isAdd = false;

        protected string SearchString { get; set; }

        protected override async Task OnInitAsync()
        {
            await GetCities();
            await GetEmployee();
        }

        protected async Task GetCities()
        {
            cityList = await employeeService.GetCities();
        }

        protected async Task GetEmployee()
        {
            empList = await employeeService.GetEmployeeList();
        }

        protected async Task FilterEmp()
        {
            await GetEmployee();
            if (SearchString != "")
            {
                empList = empList.Where(x => x.Name.IndexOf(SearchString, StringComparison.OrdinalIgnoreCase) != -1).ToList();
            }
        }

        protected void AddEmp()
        {
            emp = new Employee();
            this.modalTitle = "Add Employee";
            this.isAdd = true;
        }

        protected async Task EditEmployee(int empID)
        {
            emp = await employeeService.Details(empID);
            this.modalTitle = "Edit Employee";
            this.isAdd = true;
        }

        protected async Task SaveEmployee()
        {
            if (emp.EmployeeId != 0)
            {
                await Task.Run(() =>
                {
                    employeeService.Edit(emp);
                });
            }
            else
            {
                await Task.Run(() =>
                {
                    employeeService.Create(emp);
                });
            }
            this.isAdd = false;
            await GetEmployee();
        }

        protected async Task DeleteConfirm(int empID)
        {
            emp = await employeeService.Details(empID);
            this.isDelete = true;
        }

        protected async Task DeleteEmployee(int empID)
        {
            await Task.Run(() =>
            {
                employeeService.Delete(empID);
            });
            this.isDelete = false;
            await GetEmployee();
        }
        protected void closeModal()
        {
            this.isAdd = false;
            this.isDelete = false;
        }
    }
}

Let us understand this code. We have defined a class EmployeeDataModel that will hold all our methods that we will be using in EmployeeData.cshtml page.

We are injecting our EmployeeService to EmployeeDataModel class so that the client side methods can invoke our services.

The variables empList and cityList to hold the data from Employee table and Cities table respectively. The variables are getting populated inside the OnInitAsync to make sure that the data is available to us as the page loads.

We will use the FilterEmp method to filter the employee data based on the employee name property. This property will ignore the text case of search string and returns all the records that matches either fully or partially with the search string

Clicking of “Add Employee” button will invoke the AddEmp method. It will initialize an empty instance of Employee model and set the value of isAdd Boolean flag to true. This will open a modal popup with a form, asking the user to enter a new employee record. Similarly, we have defined an EditEmployee method, which will fetch the record of the employee based on the employee id for which it is invoked. It will also set the value of isAdd to true to open the modal popup to edit the employee record.

The SaveEmployee method will check if it is invoked to add a new employee record or to edit an existing employee record. If the EmployeeId property is set then it is an “edit” request and we will invoke the Edit method of our service. If EmployeeId is not set then it is a “create” request and we will invoke the Create method of our service. We will then fetch the updated employee record by calling GetEmployee method and also set the value of isAdd to false, thus closing the modal popup.

The DeleteConfirm method is invoked on clicking the Delete button corresponding to an employee record. It will set the value of isDelete Boolean flag to true, which will display a Delete confirmation modal popup. Upon clicking YES inside this popup, DeleteEmployee method is invoked which will delete the employee record and set the isDelete Boolean flag to false to close the modal popup.

Adding Link to Navigation menu

The last step is to add the link to our “EmployeeData” page in the navigation menu. Open ServerSideSPA.App/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="">ServerSideSPA</a>
    <button class="navbar-toggler" onclick=@ToggleNavMenu>
        <span class="navbar-toggler-icon"></span>
    </button>
</div>

<div class=@(collapseNavMenu ? "collapse" : null) 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="fetchemployee">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch employee
            </NavLink>
        </li>
    </ul>
</div>

@functions {
bool collapseNavMenu = true;

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

This completes our Single Page Application using server side Blazor.

Execution Demo

Press F5 to launch the application.

A web page will open as shown in the image below. The navigation menu on the left is showing navigation link for Employee data page. 

Click on “Employee data” link, it will redirect to EmployeeData view. Here you can see all the employee data on the page. Notice the URL has “/fetchemployee” appended to it.

Click on Add Employee button to open “Add Employee” modal popup. Enter the data in all the fields and click on Save to create a new employee record.

This will create a new employee record and display the data on the view table. Add few more records and the view will be similar as shown below:

Click on Edit button, it will again open the modal popup for editing the employee record. Edit the input fields and click on save to update the employee record.

To filter the records of the employee, enter the employee name in the search box and click on Filter button. The search text is case independent and the filter operation will return all the employee records matching the name entered in search field.  Refer to the image below:

If you click on the Delete button corresponding to the employee record, it will open a delete confirmation popup asking for a confirmation to delete the employee record.

Clicking on YES will delete the employee data and show the updated list of employees by refreshing the view table.

Conclusion

We have created a server side Blazor application using Entity Framework Core DB first approach with the help of Visual Studio 2017 and SQL Server 2017. We used a modal popup to handle user inputs via a form and implemented the search functionality on the employee records.

Please get the source code from Github and play around to get a better understanding.

You can check my other articles on Blazor here 

Preparing for interviews !!! Read my article on C# Coding Questions For Technical Interviews

You can also find this article at C# Corner.

See Also

Ankit Sharma

Software engineer having more than 4 years of extensive experience in MS technologies including but not limited to C#, ASP.NET MVC and MSSQL. I am also an author at C# corner and currently working on ASP.NET Core and Angular 5.

13 thoughts to “Single Page Application Using Server-Side Blazor”

  1. I was wondering there are 2 projects
    Server and App
    and what you did about the entity framework was on the App, as a matter of fact you did everything on the App project, I thought that the server project was for entity framework and Identity etc. just like in a webapi,
    Can that be done in the server, o or is it better or the way to do it in the App project
    I don’t understand why have the Server project for

    1. All the application logic should be written in App only. The server project is to assist the project execution only. The Blazor team will merge these two into a single project in future releases.

  2. Thanks for the clarification, since I am used to using Code first approach I was not able to do migrations in the App project I ended up finding in another bolg a work around,
    When the merge comes it will make things a lot easier
    One last question is server side blazor very immature ? because I am facing quite a few hangs without any errors in the console, will it be better to wait for the next release ?

    1. Yes Server-side Blazor is introduced as a part of Blazor 0.5.0 release and it is expected to undergo major changes in future.

  3. hello i am unable to download the zip file from Github, getting a 502 failure, is this something on my end? thanks very much!

    1. I don’t think their will be any issues compiling this code with .NET Core 2.1.400. Have you tried it? Are you facing any difficulties?

  4. I followed your instructions (VS community 15.8.1) downloaded and installed the Core Blazor Language Services, and attempted to create the project/solution (at the point your article says, “This will create our server-side Blazor solution. You can observe the folder structure in solution explorer, as shown in the below image”

    The Solution is created, but there are 0 projects in the solution. The Projects and scaffolding are created, but they are not recorded in the Solution file. Any idea what might be wrong? (by the way, I created a regular Blazor project just fine)

  5. Completed app yesterday, very good explanation of the CRUD operations in Blazor.

    I tried code first approach and everything is running, blazor is a charm

    Wish you would write an article for Shopping Cart using Blazor.

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.