In this article, we’ll implement Asp.Net Core 3.1 Web API CRUD Operations with Angular 10. To demonstrate the topic, we’ll build a project from scratch with payment details like Credit/ Debit Card.

Sub-topics discussed.

  • ASP.NET Core Web API
    • Create .Net Core Web API
    • Setup Database with EF Core
    • API Controller for CRUD Web Methods
  • Angular Client Side
    • Create Angular 9 Project
    • Consume ASP.NET Core API From Anguar
    • Form Design and Validation
    • Insert/ Create Record by Form Submission
    • Retrive and Display Inserted Records
    • Update and Delete Operation

Create ASP.NET Core Web API

In Visual Studio 2019, go to File > New > Project (Ctrl + Shift + N). From new project window, select Asp.Net Core Web Application.

Image showing how to create ASP.NET Core Web API project in Visual Studio.

Once you provide the project name and location. A new window will be opened as follows, Select API. The above steps will create a brand new ASP.NET Core Web API project.

Select API Project Template

Setup Database

Let’s create a Database for this project. Inside this project, we’ll be using Entity Framework Core to do DB Operations. So first of all we’ve to install corresponding NuGet packages. Right-click on Project Name from Solution Explorer, Click on Manage NuGet Packages, From Browse Tab, install following 3 packages.

Showing list of NuGet Packages for Entity Framework Core

Now, let’s define DB model class file -PaymentDetail.cs in a new folder Models.

Now let’s define DbContext class file- /Models/PaymentDetailContext.cs.

DbContext Class- PaymentDetailContext decides what should be added to actual physical database during DB Migration. So we have added property for PaymentDetail Model class, after migration PaymentDetails table will be created in SQL Server Database.

Into this model class constructor parameter- options, we have to pass which DbProvider (SQL Server, MySQL, PostgreSQL, etc) to use and corresponding DB connection string also. For that we’ll be using Dependency Injection in ASP.NET Core with Startup.cs file as follows.

Here we’ve used Dependency Injection for DbContext class, by passing SQL Server as a DbProvider with Connection String, Now let’s save connections in appsettings.json file using DevConnectionkey as follows.

Now let’s do the migration. Select project from solution explorer, then go to Tools > NuGet Package Manager > Package Manager Console. Then execute following commands one by one.


Add-Migration "InitialCreate"
Update-Database

After successful migration, as per the connection string, a new database – PaymentDetailDB will be created with PaymentDetails table. Also, there will be a new Migrations folder created with corresponding C# files.

Create API Controller for CRUD Operations

To create a new API Controller, right-click on Controllers folder Add > Controller, Select API Controller with actions, using Entity Framework. then we can create PaymentDetailController for CRUD operations.

With the help of Scaffolding Mechanism, new controller will be created.

It contains web methods POST, GET, PUT and DELETE for Create, Retrieve, Update and Delete operations respectively. As a constructor parameter we’ve context of the type PaymentDetailContext. the instance/value for this parameter will be passed from Dependency Injection from StartUp class.

For this project, we don’t have to change anything in web methods. You can test any of the CRUD operations using softwares like postman. And if you want to do so, you’ve to disable SSL certificate verification (Since we checked HTTPS while creating this project).

Create Angular App

Now let’s create front-end client-side app in Angular 10. For that execute following Angular-CLI command one by one


ng new app_name
# after project creation.
# navigate inside project folder
cd app_name
# open in vs code
code .
# from vs code terminal
# command to open the app in default web browser
ng serve --o

Before moving forward, let’s look at the structure of the app that we want to build.


● src
+---● app
|   +--● payment-details
|   |  |--payment-details.component.ts|.html|.css
|   |  |
|   |  +--● payment-detail-form
|   |     |--payment-detail-form.component.ts|.html|.css
|   |  
|   +--● shared
|   |     |--payment-detail.service.ts
|   |     |--payment-detail.model.ts
|   |
|   |--app.module.ts
|
|--index.html (cdn path for bootstrap & fa icons)

we’ve two components, list of records will be shown in  payment-details component, it has a child component payment-detail-form for designing the form.

To create these 2 components, you can execute the following commands.


ng g c payment-details -s --skipTests
ng g c payment-details/payment-detail-form -s --skipTests

options used

inlineStyle/ -s = skip seperate component specific style sheet
skipTests = skip test files with extension .spec.ts .

Now let’s replace the default component file- app.component.html as follows.

To show list of records and it’s form side by side, update payment-details.component.html as bellow.

For this app developement, we’ll be using Bootstrap and Font Awesome Icons. so let’s add their stylesheet reference in index.html.

I’ve few custom CSS to add in global style sheet – styles.css.


.form-group label {
  color: grey;
}

.form-group input {
  font-weight: 500;
}

.form-group input::placeholder {
  color: #c0bdbd;
  font-weight: 300;
}

thead th{
  font-weight: 400;
}

table tr:hover {
  background-color: #fffbf2;
  cursor: pointer;
}

//for invalid form controlls
input.invalid {
  border-color: red;
}

How to Consume .Net Core API from Angular

first of let’s create a model class for payment details – shared/payment-detail.model.ts. You could manually create the file or execute following CLI command.


ng g class shared/payment-detail --type=model --skipTests
# there is no seperat command for model
# hence we use class creation command with type option
# type is used to name the file like '.model.ts'

Update the model class with corresponding properties similar to .Net Core API model properties.

Now let’s create a service class to interact with ASP.NET Core Web API- shared/payment-detail.service.ts. Here is the CLI command to create the service class.


ng g s shared/payment-detail --skipTests

Update the service class as below.

formData property can be used for designing the form for CRUD Operations, list array is used to store all of the retrieved records from the API. rootUrl contains the base URL of the Web API. Now lets run the API from Visual Studio – Debug > Start Debugging(F5). HttpClient is used to make Http Request to the server. Along with methods for CRUD operations, we’ve refreshList function to populate existing records into list property.

To use HttpClient, we also need to import HttpClientModule. So update app/app.module.ts as follows.

Form Design and Validation

Now let’s design the form in payment-detail-form component. first of all we’ve to inject the service class.

Since we’ve the service injected here. we can access the service property formData to design the form. function resetForm can be used to initialize model property or reset form based on parameter form. Inside ngOnInitlife-cycle event, we’ve called the function to initialize the model property.

As a first step towards designing the form, we’ve to import FormsModule in app/app.module.ts.

Now let’s design the form. so update payment-detail-form.component.html as shown below.

It might be confusing for you, because here we’ve put everything related to the form – design and form validation. we have input field for all model properties including PMId in a hidden field. Each input field is bound to its respective property through 2 way data-binding.

Inside this form, all field has the required validation and number of characters is restricted to all field except CardOwnerName. For Angular field validation, we can use auto-generated classes/attributes for showing validation error indications. Auto-generated classes/ attribute by Angular

ng-invalid (class) or
invalid (property)
X ng-valid (class) or
valid(property)
ng-untouched(class) or
untouched(property)
X ng-touched(class) or
touched(property)

 

To indicate validation error, we conditionally applied CSS class – invalid . Finally the submit button is conditionally disabled based on whether the form as a whole is valid or not.

Currently our Angular Form in payment-detail-form component looks like this.

Image showing screen shot of Angular Form for Insert/ update operation.

Insert a new Record

let’s wire up submit event to the form.

Now define the function – onSubmit inside payment-detail-form.component.ts.

a separate function insertRecord is defined to insert a new record into the SQL server table.

Before testing this operation, we have to do a few more things in ASP.NET Core Web API.

  1. .Net Core Web API will block request from another application which is hosted in another domain or in another port number. by default, Angular is running at port number 4200 and Web API is hosted at a different port number. to make Http Request, we’ve to Enable-CORS (Cross Origin Resource Sharing) in Web API.
  2. By default, ASP.Net Core API use camel casing for response object. (eg: CardNumber to cardNumber). so we’ve to avoid this default json formatting.

Now let’s do required steps to solve these two issues. First of all install latest NuGet Package of Microsoft.AspNetCore.Cors. Then you can update Startup class like this.

Inside the Configure function, it is better to keep the function call UseCors before any other lines. Now you can try the insert operation. for me, it is working fine. Comment if you face any problem.

Retrieve and Display all Inserted Records

Inserted records can be retrieved and displayed in payment-details component. for that let’s update the component typescript file as follows.

Inside list component ngOnInit lifecycle hook, we’ve called refreshList function to populate list array in service class. using service list property, we can render all of the inserted records in payment-details component html. So update the table div as follow.

Update and Delete Operation

Tol implement update operation, for that we’ve added click event for all td cells as shown below.

Inside the click event function, we have to populate the corresponding selected record inside the form. so add the following function to payment-detailscomponent.

inside the function, we just set the selected record object to formData property in service class. since the form is bound to formData properties, the form field will get populated corresponding details.

After making required changes in these populated value fields, user can submit the form for the update operation. so we have to handle both insert and update operation inside the same form submit event in payment-detail-form component. hence update the payment-detail-form.component.ts.

Inside the form, we have a hidden field for PMId based on its value in submit function, we can decide whether we’ve got an insert/ update operation. insertRecord is already defined. with updateRecord function, we will update the corresponding payment-detail record.

Now let’s implement Delete Operation in parent component. For that add delete button inside that table rows.

file: payment-details.component.html

Now lets define onDelete function in payment-details.component.ts as below.

So that’s all about Angular CRUD operations with ASP.NET Core Web API.

Step By Step Video Tutorial

In our YouTube channel, we did these CRUD Operations with Asp.Net Core Web API 2.2 and Angular 7.