ASP.NET Core Blazor CRUD Using Entity Framework And Web API

Introduction

Blazor

In this article, we will see how to create a simple CRUD application for ASP.NET Core Blazor using Entity Framework and Web API. Blazor is a new framework introduced by Microsoft. I love to work with Blazor as this makes our SPA full stack application development in a more simple way and yes, now, we can use only one language, C#. Before Blazor, we were using ASP.NET Core with the combination of Angular or ReactJS. Now, with the help of Blazor support, we can create our own SPA application directly with C# Code.

If you start your SPA application development using Blazor, surely, you will love it and it is so simple and fun to work with Blazor. The only drawback now we have is that because Blazor is a newly introduced framework, it’s still in the experimental phase. Once we get the complete version, it will be more fun to work with application development.

In this article, we will see about creating a CRUD Web Application using ASP.NET Core Blazor.

  • C: (Create): Insert new Student Details into the database using ASP.NET Core, Blazor, EF and Web API.
  • R: (Read): Select Student Details from the database using ASP.NET Core, Blazor, EF and Web API.
  • U: (Update): Update Student Details to the database using ASP.NET Core, Blazor, EF and Web API
  • D: (Delete): Delete Student Details from the database using ASP.NET Core, Blazor, EF and Web API.

We will be using Web API and EF to perform our CRUD operations. Web API has the following four methods as Get/Post/Put and Delete, where:

  • Get is to request for the data. (Select)
  • Post is to create a data. (Insert)
  • Put is to update the data. (Update)
  • Delete is to delete data. (Delete)

Prerequisites

Make sure, you have installed all the prerequisites on your computer. If not, then download and install them all, one by one. Note that since Blazor is a new framework we must have installed the preview of Visual Studio 2017 (15.7) or above.

Step 1 - Create a database and a table

We will be using our SQL Server database for our WEB API and EF. First, we create a database named StudentsDB and a table as StudentMaster. Here is the SQL script to create a database table and sample record insert query in our table. Run the query given below in your local SQL Server to create a database and a table to be used in our project. 

  1. USE MASTER       
  2. GO       
  3.        
  4. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB       
  5. IF EXISTS (SELECT [nameFROM sys.databases WHERE [name] = 'StudentsDB' )       
  6. DROP DATABASE StudentsDB       
  7. GO       
  8.        
  9. CREATE DATABASE StudentsDB       
  10. GO       
  11.        
  12. USE StudentsDB       
  13. GO       
  14.        
  15.        
  16. -- 1) //////////// StudentMasters       
  17.        
  18. IF EXISTS ( SELECT [nameFROM sys.tables WHERE [name] = 'StudentMasters' )       
  19. DROP TABLE StudentMasters       
  20. GO       
  21.        
  22. CREATE TABLE [dbo].[StudentMasters](       
  23.         [StdID] INT IDENTITY PRIMARY KEY,       
  24.         [StdName] [varchar](100) NOT NULL,          
  25.         [Email]  [varchar](100) NOT NULL,          
  26.         [Phone]  [varchar](20) NOT NULL,          
  27.         [Address]  [varchar](200) NOT NULL       
  28. )       
  29.        
  30. -- insert sample data to Student Master table       
  31. INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])       
  32.      VALUES ('Shanu','syedshanumcain@gmail.com','01030550007','Madurai,India')       
  33.        
  34. INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])       
  35.      VALUES ('Afraz','Afraz@afrazmail.com','01030550006','Madurai,India')       
  36.             
  37. INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])       
  38.      VALUES ('Afreen','Afreen@afreenmail.com','01030550005','Madurai,India')       
  39.             
  40.      select * from [StudentMasters]     

Step 2 - Create ASP.NET Core Blazor Application

After installing all the prerequisites listed above and ASP.NET Core Blazor Language Services, click Start >> Programs >> Visual Studio 2017 >> Visual Studio 2017 on your desktop. Click New >> Project. Select Web >> ASP.NET Core Angular Web Application. Enter your project name and click OK.

ASP.NET Core

Select Blazor (ASP.NET Core hosted) and click ok

ASP.NET Core

After creating ASP.NET Core Blazor Application, wait for a few seconds. You will see the below structure in solution explorer.

ASP.NET Core

What is new in ASP.NET Core Blazor solution?

When we create our new ASP.NET Core Blazor application we can see there will be 3 projects that will be automatically created in the Solution Explorer.

Client Project

The first project created as a Client project is our Solutionname.Client and here, we can see our solution name as “BlazorASPCORE”. This project will be mainly focused on all the client-side views. Here, we will be adding all our page views to be displayed at the client side in the browser.

ASP.NET Core

We can see a few sample pages have been already added here and we can also see a shared folder like our MVC application where we will be having the Shared folder and Layout page for the Master page. Here, in Blazor, we have the MainLayout which will be working like the Master page and NavMenu for the left side menu display.

Server Project

As the name indicates, this project will be used as a Server project. This project is mainly used to create all our Controllers and WEB API Controllers to perform all business logic and perform CRUD operation using WEB API’s. In our demo application, we will be adding a Web API in this Server project and all the WEB API in our Client application. This Server project will be work like getting/set the data from Database and from our Client project we bind or send the result to this server to perform the CRUD operation in the database.

ASP.NET Core

Shared Project

As the name indicating this project work like a shred project. This project works as a Model for our Server project and for the Client project. The Model declared in this Shared project will be used in both the Server and in the Client project. We also install all the packages needed for our project here; for example, to use the Entity Framework, we install all the packages in this Shared project.

ASP.NET Core

Run to test the application

When we run the application, we can see that the left side has navigation and the right side contains the data. We can see as the default sample pages and menus will be displayed in our Blazor web site. We can use the pages or remove it and start with our own page.

ASP.NET Core

Now let’s see how to add new page perform the CRUD operation for maintaining student details.

Using Entity Framework

To use the Entity Framework in our Blazor application we need to install the below packages

Install the Packages

Go to Tools and then select -> NuGet Package Manager -> Package Manager Console.

ASP.NET Core

You can see the Console at the bottom of the VS 2017 IDE and on the right side of the combo box on the console, select the Default project as your shared project” Select Shared”.

ASP.NET Core
  • You can see the PM> and copy and paste the below line to install the Database Provider package. This package is used to set the database provider as SQL Server.

Install-Package Microsoft.EntityFrameworkCore.SqlServer

ASP.NET Core

We can see as the package is installed in our Shared folder.

Install the Entity Framework -

  • You can see the PM> and copy and paste the below line to install the EF package.

Install-Package Microsoft.EntityFrameworkCore.Tools

ASP.NET Core

To Create DB Context and set the DB Connection string

  • You can see the PM> and copy and paste the below line set the Connection string and create DB Context. This is an important part as we give our SQL Server name, Database Name and SQL server UID and SQL Server Password to connect to our database for performing the CRUD operation. We also give our SQL Table name to create the Model class in our Shared project.

  1. Scaffold-DbContext "Server= YourSqlServerName;Database=StudentsDB;user id= YourSqlUID;password= YourSqlPassword;Trusted_Connection=True;MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables StudentMasters  

ASP.NET Core

Press enter create a connection string, Model Class, and Database Context.

ASP.NET Core

We can see StudentMasters Model class and StudentsDBContext class has been created in our Shared project. We will be using this Model and DBContext in our Server project to create our Web API to perform the CRUD operations. 

Creating Web API for CRUD operation

To create our WEB API Controller, right-click Controllers folder. Click Add New Controller.

ASP.NET Core

Here we will be using Scaffold method to create our WEB API .We select API Controller with actions, using Entity Framework.

ASP.NET Core

Select our Model and DatabaseContext from the Shared project.

ASP.NET Core

Select our StudentMasters Model from the Shared Project for performing the CRUD operation.

ASP.NET Core

Select the Data Context Class as our StudentsDBContext from the Shared project. Our Controller name will be automatically added if you need you can change it and click the ADD.

ASP.NET Core

Our WEB API with Get/Post/Put and Delete method for performing the CRUD operation will be automatically created and we no need to write any code in Web API now as we have used the Scaffold method for all the actions and methods add with code.

ASP.NET Core

To test Get Method, we can run our project and copy the GET method API path. Here, we can see our API path to get api/StudentMasters/

Run the program and paste API path to test our output.

ASP.NET Core

Now we will bind all this WEB API Json result in out View page from our Client project

Working with Client Project

First, we need to add the new Razor view page

Add Razor View

To add the Razor view page right click the Pages folder from the Client project. Click on Add >> New Item

ASP.NET Core

Select Razor View >> Enter your page name,Here we have given the name as Students.chtml

ASP.NET Core

In Razor view Page we have 3 parts of code as first is the Import part where we import all the references and models for using in the view, HTML design and data bind part and finally we have the function part to call all the web API to bind in our HTML page and also to perform client-side business logic to be displayed in View page.

Import part

First, we import all the needed support files and references in our Razor View page.Here we have first imported our Model class to be used in our view and also imported HTTPClient for calling the Web API to perform the CRUD operations.

  1. @using BLAZORASPCORE.Shared  
  2. @using BLAZORASPCORE.Shared.Models  
  3. @page "/Students"  
  4. @using Microsoft.AspNetCore.Blazor.Browser.Interop  
  5. @inject HttpClient Http  

ASP.NET Core

HTML design and data Bind part

Next, we design our Student details page to display the student details from the database and created a form to Insert and update the Student details we also have Delete button to delete the student records from the database.

For binding in Blazor we use the bind="@stds.StdId" and to call the method using onclick="@AddNewStudent"

  1. <h1> ASP.NET Core BLAZOR CRUD demo for Studetns</h1>  
  2. <hr />  
  3. <table width="100%" style="background:#05163D;color:honeydew">  
  4.     <tr>  
  5.         <td width="20"> </td>  
  6.         <td>  
  7.             <h2> Add New Student Details</h2>  
  8.         </td>  
  9.         <td> </td>  
  10.         <td align="right">  
  11.             <button class="btn btn-info" onclick="@AddNewStudent">Add New Student</button>  
  12.         </td>  
  13.         <td width="10"> </td>  
  14.     </tr>  
  15.     <tr>  
  16.         <td colspan="2"></td>  
  17.     </tr>  
  18. </table>  
  19. <hr />  
  20. <form>  
  21.     <table class="form-group">  
  22.         <tr>  
  23.             <td>  
  24.                 <label for="Name" class="control-label">Student ID</label>  
  25.             </td>  
  26.             <td>  
  27.                 <input type="text" class="form-control" bind="@stds.StdId" readonly />  
  28.             </td>  
  29.             <td width="20"> </td>  
  30.             <td>  
  31.                 <label for="Name" class="control-label">Student Name</label>  
  32.             </td>  
  33.             <td>  
  34.                 <input type="text" class="form-control" bind="@stds.StdName" />  
  35.             </td>  
  36.         </tr>  
  37.         <tr>  
  38.             <td>  
  39.                 <label for="Email" class="control-label">Email</label>  
  40.             </td>  
  41.             <td>  
  42.                 <input type="text" class="form-control" bind="@stds.Email" />  
  43.             </td>  
  44.             <td width="20"> </td>  
  45.             <td>  
  46.                 <label for="Name" class="control-label">Phone</label>  
  47.             </td>  
  48.             <td>  
  49.                 <input type="text" class="form-control" bind="@stds.Phone" />  
  50.             </td>  
  51.         </tr>  
  52.         <tr>  
  53.             <td>  
  54.                 <label for="Name" class="control-label">Address</label>  
  55.             </td>  
  56.             <td>  
  57.                 <input type="text" class="form-control" bind="@stds.Address" />  
  58.             </td>  
  59.             <td width="20"> </td>  
  60.             <td></td>  
  61.             <td>  
  62.                 <button type="submit" class="btn btn-success" onclick="@(async () => await AddStudent())" style="width:220px;">Save</button>  
  63.             </td>  
  64.         </tr>  
  65.     </table>  
  66. </form>  
  67.   
  68. <table width="100%" style="background:#0A2464;color:honeydew">  
  69.     <tr>  
  70.         <td width="20"> </td>  
  71.         <td>  
  72.             <h2>Student Details</h2>  
  73.         </td>  
  74.         
  75.     </tr>  
  76.     <tr>  
  77.         <td colspan="2"></td>  
  78.     </tr>  
  79. </table>  
  80.   
  81. @if (student == null)  
  82. {  
  83.     <p><em>Loading...</em></p>  
  84. }  
  85. else  
  86. {  
  87.     <table class="table">  
  88.         <thead>  
  89.             <tr>  
  90.                 <th>Student ID</th>  
  91.                 <th>Student Name</th>  
  92.                 <th>Email</th>  
  93.                 <th>Phone</th>  
  94.   
  95.                 <th>Address</th>  
  96.             </tr>  
  97.         </thead>  
  98.         <tbody>  
  99.             @foreach (var std in student)  
  100.             {  
  101.                 <tr>  
  102.                     <td>@std.StdId</td>  
  103.                     <td>@std.StdName</td>  
  104.                     <td>@std.Email</td>  
  105.                     <td>@std.Phone</td>  
  106.   
  107.                     <td>@std.Address</td>  
  108.                     <td><button class="btn btn-primary" onclick="@(async () => await EditStudent(@std.StdId))" style="width:110px;">Edit</button></td>  
  109.                     <td><button class="btn btn-danger" onclick="@(async () => await DeleteStudent(@std.StdId))">Delete</button></td>  
  110.                 </tr>  
  111.             }  
  112.         </tbody>  
  113.     </table>  
  114. }  

Function Part

function part to call all the web API to bind in our HTML page and also to perform client-side business logic to be displayed in View page.In this Function we create a separate function for Add, Edit and Delete the student details and call the Web API Get,Post,Put and Delete method to perform the CRUD operations and in HTML we call all the function and bind the results.

  1. @functions {  
  2.     StudentMasters[] student;  
  3.   
  4.     StudentMasters stds = new StudentMasters();  
  5.     string ids = "0";  
  6.     bool showAddrow = false;  
  7.     protected override async Task OnInitAsync()  
  8.     {  
  9.         student = await Http.GetJsonAsync<StudentMasters[]>("/api/StudentMasters/");  
  10.     }  
  11.   
  12.     void AddNewStudent()  
  13.     {  
  14.         stds = new StudentMasters();  
  15.     }  
  16.     // Add New Student Details Method  
  17.     protected async Task AddStudent()  
  18.     {  
  19.         if (stds.StdId == 0)  
  20.   
  21.         {  
  22.             await Http.SendJsonAsync(HttpMethod.Post, "/api/StudentMasters/", stds);  
  23.   
  24.         }  
  25.         else  
  26.         {  
  27.             await Http.SendJsonAsync(HttpMethod.Put, "/api/StudentMasters/" + stds.StdId, stds);  
  28.         }  
  29.         stds = new StudentMasters();  
  30.         student = await Http.GetJsonAsync<StudentMasters[]>("/api/StudentMasters/");  
  31.     }  
  32.     // Edit Method  
  33.     protected async Task EditStudent(int studentID)  
  34.     {  
  35.         ids = studentID.ToString();  
  36.         stds = await Http.GetJsonAsync<StudentMasters>("/api/StudentMasters/" + Convert.ToInt32(studentID));  
  37.     }  
  38.     // Delte Method  
  39.     protected async Task DeleteStudent(int studentID)  
  40.     {  
  41.         ids = studentID.ToString();  
  42.         await Http.DeleteAsync("/api/StudentMasters/" + Convert.ToInt32(studentID));  
  43.   
  44.         // await Http.DeleteAsync("/api/StudentMasters/Delete/" + Convert.ToInt32(studentID));  
  45.   
  46.         student = await Http.GetJsonAsync<StudentMasters[]>("/api/StudentMasters/");  
  47.     }  
  48.   
  49. }   

Navigation Menu

Now we need to add this newly added Students Razor page to our left Navigation. For adding this Open the Shared Folder and open the NavMenu.cshtml page and add the menu.

  1. <li class="nav-item px-3">  
  2.             <NavLink class="nav-link" href="/Students">  
  3.                 <span class="oi oi-list-rich" aria-hidden="true"></span> Students Details  
  4.             </NavLink>  
  5.         </li>  
ASP.NET Core

Build and Run the application

Run the application

Conclusion

Note that when creating the DBContext and setting the connection string, don’t forget to add your SQL connection string. Hope you all like this article. In the next article, we will see more examples to work with Blazor. It's really very cool and awesome to work with Blazor.