Share via


ASP.NET Core Blazor CRUD using Entity Framework and Web API

Introduction 

View

In this article we will see on 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.We love to work with Blazor as this make our SPA full stack application development in more simple way and yes now we can use only one Language as C#. Before Blazor we are been 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 was that much simple and fun to work with Blazor.  

In this article, we will see on creating 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 in your computer. If not, then download and install all, one by one. Note that since Blazor is the new framework and we must have installed preview of Visual Studio 2017 (15.7) or above.

Code part

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. 

USE MASTER      
GO      
       
-- 1) Check for the Database Exists .If the database is exist then drop and create new DB      
IF EXISTS (SELECT [name] FROM  sys.databases WHERE  [name] = 'StudentsDB' )      
DROP DATABASE  StudentsDB      
GO      
       
CREATE DATABASE  StudentsDB      
GO      
       
USE StudentsDB      
GO      
       
       
-- 1) //////////// StudentMasters      
       
IF EXISTS ( SELECT  [name] FROM  sys.tables WHERE  [name] = 'StudentMasters'  )      
DROP TABLE  StudentMasters      
GO      
       
CREATE TABLE  [dbo].[StudentMasters](      
        [StdID] INT  IDENTITY PRIMARY  KEY,      
        [StdName] [varchar](100) NOT NULL,         
        [Email]  [varchar](100) NOT NULL,         
        [Phone]  [varchar](20) NOT NULL,         
        [Address]  [varchar](200) NOT NULL     
)      
       
-- insert sample data to Student Master table      
INSERT INTO  [StudentMasters]   ([StdName],[Email],[Phone],[Address])      
     VALUES ('Shanu','syedshanumcain@gmail.com','01030550007','Madurai,India')      
       
INSERT INTO  [StudentMasters]   ([StdName],[Email],[Phone],[Address])      
     VALUES ('Afraz','Afraz@afrazmail.com','01030550006','Madurai,India')      
            
INSERT INTO  [StudentMasters]   ([StdName],[Email],[Phone],[Address])      
     VALUES ('Afreen','Afreen@afreenmail.com','01030550005','Madurai,India')      
            
            
     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.


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

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

What is new in ASP.NET Core Blazor solution?

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

Client Project

The first project created as the Client project and it will be as our Solutionname.Client and here we can see as our Solutionname as “BlazorASPCORE”. As the project named as client and this project will be mainly focused for all the client-side view. Here we will be adding all our page view to be display in the client side in browser.

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

Server Project

As the name indicating 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 get/set the data from Database and from our Client project we bind or send the result to this server to perform the CRUD.

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.

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.

Now let’s see how to add new page perform the CRUD operation for maintain 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.

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

1)       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 Servder

Install-Package Microsoft.EntityFrameworkCore.SqlServer

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

Install the Entity Framework

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

Install-Package Microsoft.EntityFrameworkCore.Tools

To Create DB Context and set the DB Connection string

   3) You can see the PM> and copy and paste the below line set the Connection string and create DB Context. This is 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.

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


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

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.

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

Select our Model and DatabaseContext from the Shared project.

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

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.

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.

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.** **
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

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

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.

@using BLAZORASPCORE.Shared 
@using BLAZORASPCORE.Shared.Models 
@page "/Students" 
@using Microsoft.AspNetCore.Blazor.Browser.Interop 
@inject HttpClient Http

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"

<h1> ASP.NET Core BLAZOR CRUD demo for Studetns</h1> 
<hr /> 
<table width="100%" style="background:#05163D;color:honeydew"> 
    <tr> 
        <td width="20"> </td> 
        <td> 
            <h2> Add New Student Details</h2> 
        </td> 
        <td> </td> 
        <td align="right"> 
            <button class="btn btn-info" onclick="@AddNewStudent">Add New Student</button> 
        </td> 
        <td width="10"> </td> 
    </tr> 
    <tr> 
        <td colspan="2"></td> 
    </tr> 
</table> 
<hr /> 
<form> 
    <table class="form-group"> 
        <tr> 
            <td> 
                <label for="Name" class="control-label">Student ID</label> 
            </td> 
            <td> 
                <input type="text" class="form-control" bind="@stds.StdId" readonly /> 
            </td> 
            <td width="20"> </td> 
            <td> 
                <label for="Name" class="control-label">Student Name</label> 
            </td> 
            <td> 
                <input type="text" class="form-control" bind="@stds.StdName" /> 
            </td> 
        </tr> 
        <tr> 
            <td> 
                <label for="Email" class="control-label">Email</label> 
            </td> 
            <td> 
                <input type="text" class="form-control" bind="@stds.Email" /> 
            </td> 
            <td width="20"> </td> 
            <td> 
                <label for="Name" class="control-label">Phone</label> 
            </td> 
            <td> 
                <input type="text" class="form-control" bind="@stds.Phone" /> 
            </td> 
        </tr> 
        <tr> 
            <td> 
                <label for="Name" class="control-label">Address</label> 
            </td> 
            <td> 
                <input type="text" class="form-control" bind="@stds.Address" /> 
            </td> 
            <td width="20"> </td> 
            <td></td> 
            <td> 
                <button type="submit" class="btn btn-success" onclick="@(async () => await AddStudent())" style="width:220px;">Save</button> 
            </td> 
        </tr> 
    </table> 
</form> 
  
<table width="100%" style="background:#0A2464;color:honeydew"> 
    <tr> 
        <td width="20"> </td> 
        <td> 
            <h2>Student Details</h2> 
        </td> 
        
    </tr> 
    <tr> 
        <td colspan="2"></td> 
    </tr> 
</table> 
  
@if (student == null) 
{ 
    <p><em>Loading...</em></p> 
} 
else 
{ 
    <table class="table"> 
        <thead> 
            <tr> 
                <th>Student ID</th> 
                <th>Student Name</th> 
                <th>Email</th> 
                <th>Phone</th> 
  
                <th>Address</th> 
            </tr> 
        </thead> 
        <tbody> 
            @foreach (var std in student) 
            { 
                <tr> 
                    <td>@std.StdId</td> 
                    <td>@std.StdName</td> 
                    <td>@std.Email</td> 
                    <td>@std.Phone</td> 
  
                    <td>@std.Address</td> 
                    <td><button class="btn btn-primary" onclick="@(async () => await EditStudent(@std.StdId))" style="width:110px;">Edit</button></td> 
                    <td><button class="btn btn-danger" onclick="@(async () => await DeleteStudent(@std.StdId))">Delete</button></td> 
                </tr> 
            } 
        </tbody> 
    </table> 
}

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.

@functions { 
    StudentMasters[] student; 
  
    StudentMasters stds = new StudentMasters(); 
    string ids = "0"; 
    bool showAddrow = false; 
    protected override async Task OnInitAsync() 
    { 
        student = await Http.GetJsonAsync<StudentMasters[]>("/api/StudentMasters/"); 
    } 
  
    void AddNewStudent() 
    { 
        stds = new StudentMasters(); 
    } 
    // Add New Student Details Method 
    protected async Task AddStudent() 
    { 
        if (stds.StdId == 0) 
  
        { 
            await Http.SendJsonAsync(HttpMethod.Post, "/api/StudentMasters/", stds); 
  
        } 
        else 
        { 
            await Http.SendJsonAsync(HttpMethod.Put, "/api/StudentMasters/" + stds.StdId, stds); 
        } 
        stds = new StudentMasters(); 
        student = await Http.GetJsonAsync<StudentMasters[]>("/api/StudentMasters/"); 
    } 
    // Edit Method 
    protected async Task EditStudent(int studentID) 
    { 
        ids = studentID.ToString(); 
        stds = await Http.GetJsonAsync<StudentMasters>("/api/StudentMasters/" + Convert.ToInt32(studentID)); 
    } 
    // Delte Method 
    protected async Task DeleteStudent(int studentID) 
    { 
        ids = studentID.ToString(); 
        await Http.DeleteAsync("/api/StudentMasters/" + Convert.ToInt32(studentID)); 
  
        // await Http.DeleteAsync("/api/StudentMasters/Delete/" + Convert.ToInt32(studentID)); 
  
        student = await Http.GetJsonAsync<StudentMasters[]>("/api/StudentMasters/"); 
    } 
  
}

Conclusion

Note as when creating the DBContext and setting the connection string, don’t forget to add your SQL connection string. Hope you all like this article and in next article we will see more examples to work with Blazors and its really very cool and awesome to work with Blazor.** **

See Also

Download

ASP.NET Core Blazor CRUD using Entity Framework and Web API