Click here to Skip to main content
15,881,559 members
Articles / Web Development / Blazor

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

Rate me:
Please Sign up or sign in to vote.
4.97/5 (15 votes)
17 May 2018CPOL9 min read 47.5K   1.7K   36   14
In this article, we will see how to create a simple CRUD application for ASP.NET Core Blazor using Entity Framework and Web API.

Introduction

Image 1

* Kindly view my Youtube Video Link to learn ASP.NET Core Blazor CRUD using Entity Framework and Web API.

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 simpler way and yes, now we can use only one language as C#. Before Blazor, we had 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 simpler and fun to work with Blazor. The only drawback now we have is as the Blazor is newly introduced framework and it’s still in the experimental phase, once we get the complete version, it will be more fun to work with application developments.

In this article, we will see how to create CRUD web Application using ASP.NET Core Blazor.

Image 2

  • 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)

Background

Prerequisites

Make sure that 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, we must have installed preview of Visual Studio 2017 (15.7) or above.

Using the Code

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.

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

Image 5

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

Image 6

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

Image 7

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 our Solutionname as “BlazorASPCORE”. As the project is named as client, this project will be mainly focused for all the client-side view. Here, we will be adding all our page view to be displayed in the client side in browser.

Image 8

We can see as few of sample page has been already added here and we can also see a shared folder which is the 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 work 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 APIs. 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 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 operation in database.

Image 9

Shared Project

As the name indicates, this project works like a shared 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.

Image 10

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.

Image 11

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.

Image 12

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

Image 13

  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 Server.
    Razor
    <font color="#000000" face="Calibri" size="3">
    Install-Package Microsoft.EntityFrameworkCore.SqlServer</font>

    Image 14

    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

    Image 15

  3. 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.
    Scaffold-DbContext "Server= YourSqlServerName;Database=StudentsDB;
    user id= YourSqlUID;password= YourSqlPassword;Trusted_Connection=True;
    MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer
    -OutputDir Models -Tables StudentMasters

    Image 16

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

    Image 17

    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.

Image 18

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

Image 19

Select our Model and DatabaseContext from the Shared project.

Image 20

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

Image 21

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.

Image 22

Our WEB API with Get/Post/Put and Delete method for performing the CRUD operation will be automatically created and we do not 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.

Image 23

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.

Image 24

Now, we will bind all this WEB API Json result in our 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.

Image 25

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

Image 26

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.

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

Image 27

HTML Design and Data Bind Part

Next, we design our Student details page to display the student details from the database and create 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".

HTML
<h1> ASP.NET Core BLAZOR CRUD demo for Studetns</h1>
<hr />
<table width="100%" style="background:#05163D;color:honeydew">
    <tr>
        <td width="20">&nbsp;</td>
        <td>
            <h2> Add New Student Details</h2>
        </td>
        <td>&nbsp;</td>
        <td align="right">
            <button class="btn btn-info" onclick="@AddNewStudent">Add New Student</button>
        </td>
        <td width="10">&nbsp;</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">&nbsp;</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">&nbsp;</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">&nbsp;</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">&nbsp;</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.

Razor
@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/");
    }
}

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.

Razor
<li class="nav-item px-3">
            <NavLink class="nav-link" href="/Students">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Students Details
            </NavLink>
        </li>

Build and Run the Application

Image 28

Points of Interest

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 the next article, we will see more examples to work with Blazors and it's really very cool and awesome to work with Blazor.

History

  • 2018-05-18: BLAZORASPCORE.zip

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
QuestionNewest version Pin
Member 952129116-Jun-19 1:07
Member 952129116-Jun-19 1:07 
AnswerRe: Newest version Pin
Member 1414421822-Jun-19 11:41
Member 1414421822-Jun-19 11:41 
Questionerrors on my blazor app when i apply this url: http://localhost:53960/api/StudentMasters/ Pin
Member 1279843528-Jan-19 5:20
Member 1279843528-Jan-19 5:20 
AnswerRe: errors Build blazor app i apply this url: http://localhost:53960/api/StudentMasters/ Pin
Member 1279843528-Jan-19 5:23
Member 1279843528-Jan-19 5:23 
AnswerRe: errors on my blazor app when i apply this url: http://localhost:53960/api/StudentMasters/ Pin
Member 952129115-Jun-19 22:30
Member 952129115-Jun-19 22:30 
GeneralRe: errors on my blazor app when i apply this url: http://localhost:53960/api/StudentMasters/ Pin
Member 952129115-Jun-19 23:16
Member 952129115-Jun-19 23:16 
QuestionError on build Pin
Mike Horn MSU2-Nov-18 6:20
Mike Horn MSU2-Nov-18 6:20 
QuestionError on Build with Latest (as on today 20180812) versions of packages Pin
Member 783241812-Aug-18 18:22
Member 783241812-Aug-18 18:22 
AnswerRe: Error on Build with Latest (as on today 20180812) versions of packages Pin
Member 1395821522-Aug-18 10:32
Member 1395821522-Aug-18 10:32 
GeneralRe: Error on Build with Latest (as on today 20180812) versions of packages Pin
Member 783241822-Aug-18 12:16
Member 783241822-Aug-18 12:16 
GeneralRe: Error on Build with Latest (as on today 20180812) versions of packages Pin
Mike Horn MSU6-Nov-18 8:05
Mike Horn MSU6-Nov-18 8:05 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun1-Jun-18 10:16
Humayun Kabir Mamun1-Jun-18 10:16 
QuestionFew question on blazor Pin
Mou_kol17-May-18 23:19
Mou_kol17-May-18 23:19 
AnswerRe: Few question on blazor Pin
Carsten V2.018-May-18 0:04
Carsten V2.018-May-18 0:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.