Creating An SPA Using Razor Pages With Blazor

Introduction

In this article, we are going to create a Single Page Application (SPA) using Razor pages in Blazor 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.
 
We will be using Visual Studio 2017 and SQL Server 2014.

Take a look at the final application. 

Prerequisites

  • Install .NET Core 2.1 Preview 2 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 2008 or above
Blazor framework is not supported by versions below Visual Studio 2017 v15.7.

Source Code

Get the source code from GitHub.

Creating Table

We will be using a DB table to store all the records of employees.

Open SQL Server and use the following script to create Employee table.
  1. CREATE TABLE Employee (  
  2. EmployeeID int IDENTITY(1,1) PRIMARY KEY,  
  3. Name varchar(20) NOT NULL ,  
  4. City varchar(20) NOT NULL ,  
  5. Department varchar(20) NOT NULL ,  
  6. Gender varchar(6) NOT NULL  
  7. )  

Create Blazor Web 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 BlazorSPA 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 (ASP .NET Core hosted)” template and press OK. 
 
 
 
Now, our Blazor solution will be created. You can observe the folder structure in Solution Explorer, as shown in the below image. 
 
 
 
You can observe that we have three project files created in this solution.
  1. BlazorSPA.Client – It has the client side code and contains the pages that will be rendered on the browser.
  2. BlazorSPA.Server – It has the server side codes such as DB related operations and web API.
  3. BlazorSPA.Shared – It contains the shared code that can be accessed by both client and server. It contains our Model classes.

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 BlazorSPA.Shared project so that it can be accessible to both client and server project.

Navigate to Tools >> NuGet Package Manager >> Package Manager Console. Select “BlazorSPA.Shared” 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
Do not forget to put your own connection string (inside " "). After this command is executed successfully, you can observe a Models folder has been created and it contains two class files myTestDBContext.cs and Employee.cs. Hence, we have successfully scaffolded our Models using EF core database first approach.
At this point in time, the Models folder will have the following structure.

 

Creating Data Access Layer for the Application

Right-click on BlazorSPA.Server 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.cs.

Open EmployeeDataAccessLayer.cs and put the following code into it.
  1. using BlazorSPA.Shared.Models;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace BlazorSPA.Server.DataAccess  
  9. {  
  10.     public class EmployeeDataAccessLayer  
  11.     {  
  12.         myTestDBContext db = new myTestDBContext();  
  13.   
  14.         //To Get all employees details     
  15.         public IEnumerable<Employee> GetAllEmployees()  
  16.         {  
  17.             try  
  18.             {  
  19.                 return db.Employee.ToList();  
  20.             }  
  21.             catch  
  22.             {  
  23.                 throw;  
  24.             }  
  25.         }  
  26.   
  27.         //To Add new employee record       
  28.         public void AddEmployee(Employee employee)  
  29.         {  
  30.             try  
  31.             {  
  32.                 db.Employee.Add(employee);  
  33.                 db.SaveChanges();  
  34.             }  
  35.             catch  
  36.             {  
  37.                 throw;  
  38.             }  
  39.         }  
  40.   
  41.         //To Update the records of a particluar employee      
  42.         public void UpdateEmployee(Employee employee)  
  43.         {  
  44.             try  
  45.             {  
  46.                 db.Entry(employee).State = EntityState.Modified;  
  47.                 db.SaveChanges();  
  48.             }  
  49.             catch  
  50.             {  
  51.                 throw;  
  52.             }  
  53.         }  
  54.   
  55.         //Get the details of a particular employee      
  56.         public Employee GetEmployeeData(int id)  
  57.         {  
  58.             try  
  59.             {  
  60.                 Employee employee = db.Employee.Find(id);  
  61.                 return employee;  
  62.             }  
  63.             catch  
  64.             {  
  65.                 throw;  
  66.             }  
  67.         }  
  68.   
  69.         //To Delete the record of a particular employee      
  70.         public void DeleteEmployee(int id)  
  71.         {  
  72.             try  
  73.             {  
  74.                 Employee emp = db.Employee.Find(id);  
  75.                 db.Employee.Remove(emp);  
  76.                 db.SaveChanges();  
  77.             }  
  78.             catch  
  79.             {  
  80.                 throw;  
  81.             }  
  82.         }  
  83.     }  
  84. }  
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.

Adding the web API Controller to the Application

Right-click on BlazorSPA.Server/Controllers folder and select Add >> New Item. An “Add New Item” dialog box will open. Select Web from the left panel, then select “API Controller Class” from templates panel and put the name as EmployeeController.cs. Click Add.
 
 
 
This will create our API EmployeeController class. We will call the methods of EmployeeDataAccessLayer class to fetch data and pass on the data to the client side.

Open EmployeeController.cs file and put the following code into it.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using BlazorSPA.Server.DataAccess;  
  6. using BlazorSPA.Shared.Models;  
  7. using Microsoft.AspNetCore.Mvc;  
  8.   
  9. namespace BlazorSPA.Server.Controllers  
  10. {  
  11.     public class EmployeeController : Controller  
  12.     {  
  13.         EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();  
  14.   
  15.         [HttpGet]  
  16.         [Route("api/Employee/Index")]  
  17.         public IEnumerable<Employee> Index()  
  18.         {  
  19.             return objemployee.GetAllEmployees();  
  20.         }  
  21.   
  22.         [HttpPost]  
  23.         [Route("api/Employee/Create")]  
  24.         public void Create([FromBody] Employee employee)  
  25.         {  
  26.             if (ModelState.IsValid)  
  27.                 objemployee.AddEmployee(employee);  
  28.         }  
  29.   
  30.         [HttpGet]  
  31.         [Route("api/Employee/Details/{id}")]  
  32.         public Employee Details(int id)  
  33.         {  
  34.   
  35.             return objemployee.GetEmployeeData(id);  
  36.         }  
  37.   
  38.         [HttpPut]  
  39.         [Route("api/Employee/Edit")]  
  40.         public void Edit([FromBody]Employee employee)  
  41.         {  
  42.             if (ModelState.IsValid)  
  43.                 objemployee.UpdateEmployee(employee);  
  44.         }  
  45.   
  46.         [HttpDelete]  
  47.         [Route("api/Employee/Delete/{id}")]  
  48.         public void Delete(int id)  
  49.         {  
  50.             objemployee.DeleteEmployee(id);  
  51.         }  
  52.   
  53.     }  
  54. }  

At this point in time, our BlazorSPA.Server project has the following structure.

 
 
We are done with our backend logic. Therefore, we will now proceed to code our client side.

Adding Razor Page to the Application

We will add the Razor page in BlazorSPA.Client/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 BlazorSPA.Client/Pages folder.
 
Right-click on BlazorSPA.Client/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 our BlazorSPA.Client/Pages folder. This razor page will have two files.

EmployeeData.cshtml and EmployeeData.cshtml.cs.

Now, we will add codes to these pages.

EmployeeData.cshtml.cs

Open EmployeeData.cshtml.cs and put the following code into it.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http;  
  5. using System.Threading.Tasks;  
  6. using BlazorSPA.Shared.Models;  
  7. using Microsoft.AspNetCore.Blazor;  
  8. using Microsoft.AspNetCore.Blazor.Components;  
  9. using Microsoft.AspNetCore.Blazor.Services;  
  10.   
  11. namespace BlazorSPA.Client.Pages  
  12. {  
  13.     public class EmployeeDataModel : BlazorComponent  
  14.     {  
  15.         [Inject]  
  16.         protected HttpClient Http { getset; }  
  17.         [Inject]  
  18.         protected IUriHelper UriHelper { getset; }  
  19.   
  20.         [Parameter]  
  21.         protected string paramEmpID { getset; } = "0";  
  22.         [Parameter]  
  23.         protected string action { getset; }  
  24.   
  25.         protected List<Employee> empList = new List<Employee>();  
  26.         protected Employee emp = new Employee();  
  27.         protected string title { getset; }  
  28.   
  29.         protected override async Task OnParametersSetAsync()  
  30.         {  
  31.             if (action == "fetch")  
  32.             {  
  33.                 await FetchEmployee();  
  34.                 this.StateHasChanged();  
  35.             }  
  36.             else if (action == "create")  
  37.             {  
  38.                 title = "Add Employee";  
  39.                 emp = new Employee();  
  40.             }  
  41.             else if (paramEmpID != "0")  
  42.             {  
  43.                 if (action == "edit")  
  44.                 {  
  45.                     title = "Edit Employee";  
  46.                 }  
  47.                 else if (action == "delete")  
  48.                 {  
  49.                     title = "Delete Employee";  
  50.                 }  
  51.   
  52.                 emp = await Http.GetJsonAsync<Employee>("/api/Employee/Details/" + Convert.ToInt32(paramEmpID));  
  53.             }  
  54.         }  
  55.   
  56.         protected async Task FetchEmployee()  
  57.         {  
  58.             title = "Employee Data";  
  59.             empList = await Http.GetJsonAsync<List<Employee>>("api/Employee/Index");  
  60.         }  
  61.   
  62.         protected async Task CreateEmployee()  
  63.         {  
  64.             if (emp.EmployeeId != 0)  
  65.             {  
  66.                 await Http.SendJsonAsync(HttpMethod.Put, "api/Employee/Edit", emp);  
  67.             }  
  68.             else  
  69.             {  
  70.                 await Http.SendJsonAsync(HttpMethod.Post, "/api/Employee/Create", emp);  
  71.             }  
  72.             UriHelper.NavigateTo("/employee/fetch");  
  73.         }  
  74.   
  75.         protected async Task DeleteEmployee()  
  76.         {  
  77.             await Http.DeleteAsync("api/Employee/Delete/" + Convert.ToInt32(paramEmpID));  
  78.             UriHelper.NavigateTo("/employee/fetch");  
  79.         }  
  80.   
  81.         protected void Cancel()  
  82.         {  
  83.             title = "Employee Data";  
  84.             UriHelper.NavigateTo("/employee/fetch");  
  85.         }  
  86.     }  
  87. }  
Let us understand this code. We have defined a class EmployeeDataModel that will hold all our methods that we will use in EmployeeData.cshtml page.
 
We are injecting the HttpClient service to enable web API call and IUriHelper service to enable URL redirection. After this, we have defined our parameter attributes – paramEmpID and action. These parameters are used in EmployeeData.cshtml to define the routes for our page. We have also declared a property title to display the heading to specify the current action that is being performed on the page.
 
OnParametersSetAsync method is invoked every time the URL parameters are set for the page. We will check the value of parameter “action” to identify the current operation on the page. If the action is set to “fetch”, then we will invoke FetchEmployee method to fetch the updated list of employees from the database and refresh the UI using StateHasChanged method. We will check if the action attribute of parameter is set to “create”, then we will set the title of page to “Add Employee” and create a new object of type Employee. If the paramEmpID is not “0”, then it is either an edit action or a delete action. We will set the title property according to the corresponding value of action and then invoke our web API method to fetch the data for the employee id as set in paramEmpID property.
 
The method FetchEmployee will set the title to “Employee Data” and fetch all the employee data by invoking our web API method.
The CreateEmployee 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 send a PUT request to web API. If EmployeeId is not set then it is a “create” request and we will send a POST request to web API. We will then fetch the updated employee record by calling FetchEmployee method and invoke the StateHasChanged to display the updated changes on the UI.
 
The DeleteEmployee method will delete the employee record for the employee id as set in paramEmpID property. After deletion, the user is redirected to “/employee/fetch” page.
 
In the Cancel method we will set the title property to “Employee Data” and redirect the user to “/employee/fetch” page.
 
EmployeeData.cshtml

Open EmployeeData.cshtml page and put the following code into it.
  1. @page "/employee/{action}/{paramEmpID}"  
  2. @page "/employee/{action}"  
  3. @inherits EmployeeDataModel  
  4.   
  5. <h1>@title</h1>  
  6.   
  7. @if (action == "fetch")  
  8. {  
  9.     <p>  
  10.         <a href="/employee/create">Create New</a>  
  11.     </p>  
  12. }  
  13.   
  14. @if (action == "create" || action == "edit")  
  15. {  
  16.     <form>  
  17.         <table class="form-group">  
  18.             <tr>  
  19.                 <td>  
  20.                     <label for="Name" class="control-label">Name</label>  
  21.                 </td>  
  22.                 <td>  
  23.                     <input type="text" class="form-control" bind="@emp.Name" />  
  24.                 </td>  
  25.                 <td width="20"> </td>  
  26.                 <td>  
  27.                     <label for="Department" class="control-label">Department</label>  
  28.                 </td>  
  29.                 <td>  
  30.                     <input type="text" class="form-control" bind="@emp.Department" />  
  31.                 </td>  
  32.             </tr>  
  33.             <tr>  
  34.                 <td>  
  35.                     <label for="Gender" class="control-label">Gender</label>  
  36.                 </td>  
  37.                 <td>  
  38.                     <select asp-for="Gender" class="form-control" bind="@emp.Gender">  
  39.                         <option value="">-- Select Gender --</option>  
  40.                         <option value="Male">Male</option>  
  41.                         <option value="Female">Female</option>  
  42.                     </select>  
  43.                 </td>  
  44.                 <td width="20"> </td>  
  45.                 <td>  
  46.                     <label for="City" class="control-label">City</label>  
  47.                 </td>  
  48.                 <td>  
  49.                     <input type="text" class="form-control" bind="@emp.City" />  
  50.                 </td>  
  51.             </tr>  
  52.             <tr>  
  53.                 <td></td>  
  54.                 <td>  
  55.                     <input type="submit" class="btn btn-success" onclick="@(async () => await CreateEmployee())" style="width:220px;" value="Save" />  
  56.                 </td>  
  57.                 <td></td>  
  58.                 <td width="20"> </td>  
  59.                 <td>  
  60.                     <input type="submit" class="btn btn-danger" onclick="@Cancel" style="width:220px;" value="Cancel" />  
  61.                 </td>  
  62.             </tr>  
  63.         </table>  
  64.     </form>  
  65. }  
  66. else if (action == "delete")  
  67. {  
  68.     <div class="col-md-4">  
  69.         <table class="table">  
  70.             <tr>  
  71.                 <td>Name</td>  
  72.                 <td>@emp.Name</td>  
  73.             </tr>  
  74.             <tr>  
  75.                 <td>Gender</td>  
  76.                 <td>@emp.Gender</td>  
  77.             </tr>  
  78.             <tr>  
  79.                 <td>Department</td>  
  80.                 <td>@emp.Department</td>  
  81.             </tr>  
  82.             <tr>  
  83.                 <td>City</td>  
  84.                 <td>@emp.City</td>  
  85.             </tr>  
  86.         </table>  
  87.         <div class="form-group">  
  88.             <input type="submit" class="btn btn-danger" onclick="@(async () => await DeleteEmployee())" value="Delete" />  
  89.             <input type="submit" value="Cancel" onclick="@Cancel" class="btn" />  
  90.         </div>  
  91.     </div>  
  92. }  
  93.   
  94. @if (empList == null)  
  95. {  
  96.     <p><em>Loading...</em></p>  
  97. }  
  98. else  
  99. {  
  100.     <table class='table'>  
  101.         <thead>  
  102.             <tr>  
  103.                 <th>ID</th>  
  104.                 <th>Name</th>  
  105.                 <th>Gender</th>  
  106.                 <th>Department</th>  
  107.                 <th>City</th>  
  108.             </tr>  
  109.         </thead>  
  110.         <tbody>  
  111.             @foreach (var emp in empList)  
  112.             {  
  113.                 <tr>  
  114.                     <td>@emp.EmployeeId</td>  
  115.                     <td>@emp.Name</td>  
  116.                     <td>@emp.Gender</td>  
  117.                     <td>@emp.Department</td>  
  118.                     <td>@emp.City</td>  
  119.                     <td>  
  120.   
  121.                         <a href='/employee/edit/@emp.EmployeeId'>Edit</a>  |  
  122.                         <a href='/employee/delete/@emp.EmployeeId'>Delete</a>  
  123.                     </td>  
  124.                 </tr>  
  125.             }  
  126.         </tbody>  
  127.     </table>  
  128. }  

At the top, we have defined the routes for our page. There are two routes defined.

  1. /employee/{action}/{paramEmpID}
    This will accept action name along with employee id. This route is invoked when we perform Edit or Delete operation. When we call edit or delete action on a particular employee data, the employee id is also passed as the URL parameter.

  2. /employee/{action}
    This will only accept the action name. This route is invoked when we create a new employee data or we fetch the records of all the employees.
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 are setting the title that will be displayed on our page. The title is dynamic; it changes as per the action that is being executed currently on the page.

We will show the “Create New” link only if the action is “fetch”. If the action is created or edited, then “Create New” link will be hidden and we will display the form to get the user input. Inside the form, we have also defined two buttons “Save” and “Cancel”. Clicking on Save will invoke the “CreateEmployee” method whereas clicking on Cancel will invoke the “Cancel” method.

If the action is "delete", then a table will be displayed with the data of the employee on which the delete action is invoked. We are also displaying two buttons – “Delete” and “Cancel”. On clicking of Delete button, “DeleteEmployee” method will be invoked and clicking on Cancel will invoke the “Cancel” method.

In the end, we have a table to display all the employee data from the database. Each employee record will also have two action links, Edit to edit the employee record and Delete to delete the employee record. This table is always displayed on the page and we will update it after performing every action. 

Adding Link to Navigation menu

The last step is to add the link to our “EmployeeData” page in the navigation menu, open BlazorSPA.Client/Shared/NavMenu.cshtml page and put the following code into it.
  1. <div class="top-row pl-4 navbar navbar-dark">  
  2.     <a class="navbar-brand" href="/">BlazorSPA</a>  
  3.     <button class="navbar-toggler" onclick=@ToggleNavMenu>  
  4.         <span class="navbar-toggler-icon"></span>  
  5.     </button>  
  6. </div>  
  7.   
  8. <div class=@(collapseNavMenu ? "collapse" : null) onclick=@ToggleNavMenu>  
  9.     <ul class="nav flex-column">  
  10.         <li class="nav-item px-3">  
  11.             <NavLink class="nav-link" href="/" Match=NavLinkMatch.All>  
  12.                 <span class="oi oi-home" aria-hidden="true"></span> Home  
  13.             </NavLink>  
  14.         </li>  
  15.         <li class="nav-item px-3">  
  16.             <NavLink class="nav-link" href="/employee/fetch">  
  17.                 <span class="oi oi-list-rich" aria-hidden="true"></span> Employee data  
  18.             </NavLink>  
  19.         </li>  
  20.     </ul>  
  21. </div>  
  22.   
  23. @functions {  
  24.     bool collapseNavMenu = true;  
  25.   
  26.     void ToggleNavMenu()  
  27.     {  
  28.         collapseNavMenu = !collapseNavMenu;  
  29.     }  
  30. }  

Hence, we have successfully created a Single Page Application (SPA) using Blazor with the help of Entity Framework Core database first approach.

Execution Demo

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 “employee/fetch” appended to it.

 

Since we have not added any data, hence it is empty. Click on CreateNew to open “Add Employee” form to add a new employee data. Notice the URL has “employee/create” appended to it.

 

After inserting data in all the fields, click on "Save" button. The new employee record will be created and the Employee data table will get refreshed. The URL will also change to “/employee/fetch”.

 

If we want to edit an existing employee record, then click on Edit action link. It will open Edit view as shown below. Here we can change the employee data. Notice that we have passed employee id in the URL parameter.

 

Here we have changed the City of employee Swati from Mumbai to Kolkatta. Click on "Save" to refresh the employee data table to view the updated changes as highlighted in the image below,

 

Now, we will perform Delete operation on the employee named Dhiraj. Click on Delete action link which will open Delete view asking for a confirmation to delete. Notice that we have passed employee id in the URL parameter.

 

Once we click on the Delete button, it will delete the employee record and the employee data table will be refreshed. Here, we can see that the employee with name Dhiraj has been removed from our record.

 

Deploying the application

To learn how to deploy a Blazor application using IIS, refer to Deploying A Blazor Application On IIS

Conclusion

We have created a Single Page Application with Razor pages in Blazor using the Entity Framework Core database first approach with the help of Visual Studio 2017 and SQL Server 2014. We have also performed the CRUD operations on our application.

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

You can also read other articles on my personal blog here.

See Also

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now