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.
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.
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.
Now, let’s define DB model class file –PaymentDetail.cs in a new folder Models.
Now let’s define DbContextclass 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 PaymentDetailModel 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.
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 StartUpclass.
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).
Web methods with the corresponding URL are given below.
GET | /api/PaymentDetail/ | Retrieve all records |
GET | /api/PaymentDetail/id | Retrieve a record with given id |
POST | /api/PaymentDetail/ | Insert/ Create a new record |
PUT | /api/PaymentDetail/id | Update a record with given id |
DELETE | /api/PaymentDetail/id | Delete a record with given id |
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.
Before moving forward, let’s look at the structure of the app that we want to build.
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.
options used
–inlineStyle(Aliase : -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.
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
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.
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 formDatato 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 FormsModulein 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 requiredvalidation and number of characters is restricted to all field except Card Owner Name. 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)/ invalid (property) X ng-valid (class)/ valid (property)
- ng-untouched (class)/ untouched (property) X ng-touched (class)/ 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.
Insert a new Record
let’s wire up submitevent to the form.
Now define the function – onSubmitinside payment-detail-form.component.ts.
a separate function insertRecordis 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.
- .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.
- 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 refreshListfunction to populate listarray in service class. using service listproperty, 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 tdcells 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 formDataproperty in service class. since the form is bound to formDataproperties, 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. insertRecordis already defined. with updateRecordfunction, we will update the corresponding payment-detail record.
Now let’s implement DeleteOperation in parent component. For that add delete button inside that table rows.
file: payment-details.component.html
Now lets define onDeletefunction in payment-details.component.ts as below.
So that’s all about Angular CRUD operations with ASP.NET Core Web API.
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.