How to add CRUD Operations to Angular 8 using ASP.NET Web API and MongoDB

How to add CRUD Operations to Angular 8 using ASP.NET Web API and MongoDB

In this Angular 8 tutorial, we discuss how to add CRUD functionality to an Angular 8 application using ASP.NET Web API and MongoDB.

MongoDB is a NoSQL, free, open source, high-performance, and cross-platform document-oriented database. MongoDB was developed by the 10gen company that is now called MongoDB Inc. MongoDB is written in C++ and stores data in a flexible, JSON-like format with a dynamic schema.

Prerequisites

  • We should have the basic knowledge of Angular, MongoDB, and Web API.
  • The Visual Studio Code IDE should be installed.
  • Robo 3T or Studio 3T should be installed.

This article covers:

  • How to create a database and collection in MongoDB.

  • How to create a Web API Project.

  • How to create Angular 7 Project.

  • Install Bootstrap.

  • Creating components in an Angular 7 project.

  • Creating a class in an Angular 7 project.

  • Creating a service in an Angular 7 project.

  • Add routing.

  • Implement searching and paging.

Create a Database and Collection in MongoDB

MongoDB Environment Setup

Check how to set up the MongoDB environment and Robo 3T, from here.

Step 1

Now, open Robo 3T and connect to the local server.
Connecting to localhost

Step 2

Create a database with the name "employee" using Robo 3T (Check Link).

Create a Web API Project

Step 1

Open Visual Studio and create a new project.
Creating a project

Change the name to CrudWithMongoDB.

Changing project name

Choose the WEB API template.

Step 2

Now, add the MongoDB Driver for C# using NuGet Package Manager.

Go to Tools>>NuGet Package Manager >> Manage NuGet package for Solution.

Managing NuGet package

Step 3

Right-click the Models folder and add two classes, Employee and Status. Now, paste the following codes in these classes.

Add the required namespaces in the Employee class.

using MongoDB.Bson;  
using MongoDB.Bson.Serialization.Attributes;  

Employee class

 public class Employee  
       {  
           [BsonRepresentation(BsonType.ObjectId)]  
           public String Id { get; set; }  
           public string Name { get; set; }  
           public string  { get; set; }  
           public string Address { get; set; }  
           public string City { get; set; }  
           public string Country { get; set; }  
       }  

Status class

  public class Status  
       {  
           public string Result { set; get; }  
           public string Message { set; get; }  
       }  

Step 4

Now, add a connection string in the web.config file and add the following line in the App Settings section of that file.

<add key="connectionString" value="mongodb://localhost"/>    

Step 5

Right-click on the Controllers folder and add a new controller. Name it "Emp controller."

Add the following namespaces in the Emp controller.

using MongoDB.Driver;  
using MongoDB.Bson;  
using CrudWithMongoDB.Models;  

Now, add a method to insert data into the database for inserting employee details.

    [Route("InsertEmployee")]  
           [HttpPost]  
           public object Addemployee(Employee objVM)  
           {  
               try  
               {   ///Insert Emoloyeee  
                   #region InsertDetails  
                   if (objVM.Id == null)  
                   {  
                       string constr = ConfigurationManager.AppSettings["connectionString"];  
                       var Client = new MongoClient(constr);  
                       var DB = Client.GetDatabase("Employee");  
                       var collection = DB.GetCollection<Employee>("EmployeeDetails");  
                       collection.InsertOne(objVM);  
                       return new Status  
                       { Result = "Success", Message = "Employee Details Insert Successfully" };  
                   }  
                   #endregion  
                   ///Update Emoloyeee  
                   #region updateDetails  
                   else  
                   {  
                       string constr = ConfigurationManager.AppSettings["connectionString"];  
                       var Client = new MongoClient(constr);  
                       var Db = Client.GetDatabase("Employee");  
                       var collection = Db.GetCollection<Employee>("EmployeeDetails");  

                       var update = collection.FindOneAndUpdateAsync(Builders<Employee>.Filter.Eq("Id", objVM.Id), Builders<Employee>.Update.Set("Name", objVM.Name).Set("Department", objVM.Department).Set("Address", objVM.Address).Set("City", objVM.City).Set("Country", objVM.Country));  

                       return new Status  
                       { Result = "Success", Message = "Employee Details Update Successfully" };  
                   }  
                   #endregion  
               }  

               catch (Exception ex)  
               {  
                   return new Status  
                   { Result = "Error", Message = ex.Message.ToString() };  
               }  

           }  

Add a new method to delete employee details.

#region DeleteEmployee  
     [Route("Delete")]  
     [HttpGet]  
     public object Delete(string id)  
     {  
         try  
         {  
             string constr = ConfigurationManager.AppSettings["connectionString"];  
             var Client = new MongoClient(constr);  
             var DB = Client.GetDatabase("Employee");  
             var collection = DB.GetCollection<Employee>("EmployeeDetails");  
             var DeleteRecored = collection.DeleteOneAsync(  
                            Builders<Employee>.Filter.Eq("Id", id));  
             return new Status  
             { Result = "Success", Message = "Employee Details Delete  Successfully" };  

         }  
         catch (Exception ex)  
         {  
             return new Status  
             { Result = "Error", Message = ex.Message.ToString() };  
         }  

     }  
     #endregion  

Add a method to get Employee details.

  #region Getemployeedetails  
           [Route("GetAllEmployee")]  
           [HttpGet]  
           public object GetAllEmployee()  
           {  
               string constr = ConfigurationManager.AppSettings["connectionString"];  
               var Client = new MongoClient(constr);  
               var db = Client.GetDatabase("Employee");  
               var collection = db.GetCollection<Employee>("EmployeeDetails").Find(new BsonDocument()).ToList();  
               return Json(collection);  

           }  
           #endregion  

Add a method to get Employee details by Id.

#region EmpdetaisById  
     [Route("GetEmployeeById")]  
     [HttpGet]  
     public object GetEmployeeById(string id)  
     {  
         string constr = ConfigurationManager.AppSettings["connectionString"];  
         var Client = new MongoClient(constr);  
         var DB = Client.GetDatabase("Employee");  
         var collection = DB.GetCollection<Employee>("EmployeeDetails");  
         var plant = collection.Find(Builders<Employee>.Filter.Where(s => s.Id == id)).FirstOrDefault();  
         return Json(plant);  

     }  
     #endregion 

Here is the complete Emp controller code.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Web.Http;  
using MongoDB.Driver;  
using MongoDB.Bson;  
using CrudWithMongoDB.Models;  
using System.Configuration;  

namespace CrudWithMongoDB.Controllers  
{  
    [RoutePrefix("Api/Employee")]  
    public class EmpController : ApiController  
    {  
        [Route("InsertEmployee")]  
        [HttpPost]  
        public object Addemployee(Employee objVM)  
        {  
            try  
            {   ///Insert Emoloyeee  
                #region InsertDetails  
                if (objVM.Id == null)  
                {  
                    string constr = ConfigurationManager.AppSettings["connectionString"];  
                    var Client = new MongoClient(constr);  
                    var DB = Client.GetDatabase("Employee");  
                    var collection = DB.GetCollection<Employee>("EmployeeDetails");  
                    collection.InsertOne(objVM);  
                    return new Status  
                    { Result = "Success", Message = "Employee Details Insert Successfully" };  
                }  
                #endregion  
                ///Update Emoloyeee  
                #region updateDetails  
                else  
                {  
                    string constr = ConfigurationManager.AppSettings["connectionString"];  
                    var Client = new MongoClient(constr);  
                    var Db = Client.GetDatabase("Employee");  
                    var collection = Db.GetCollection<Employee>("EmployeeDetails");  

                    var update = collection.FindOneAndUpdateAsync(Builders<Employee>.Filter.Eq("Id", objVM.Id), Builders<Employee>.Update.Set("Name", objVM.Name).Set("Department", objVM.Department).Set("Address", objVM.Address).Set("City", objVM.City).Set("Country", objVM.Country));  

                    return new Status  
                    { Result = "Success", Message = "Employee Details Update Successfully" };  
                }  
                #endregion  
            }  

            catch (Exception ex)  
            {  
                return new Status  
                { Result = "Error", Message = ex.Message.ToString() };  
            }  

        }  

        #region Getemployeedetails  
        [Route("GetAllEmployee")]  
        [HttpGet]  
        public object GetAllEmployee()  
        {  
            string constr = ConfigurationManager.AppSettings["connectionString"];  
            var Client = new MongoClient(constr);  
            var db = Client.GetDatabase("Employee");  
            var collection = db.GetCollection<Employee>("EmployeeDetails").Find(new BsonDocument()).ToList();  
            return Json(collection);  

        }  
        #endregion  
        #region EmpdetaisById  
        [Route("GetEmployeeById")]  
        [HttpGet]  
        public object GetEmployeeById(string id)  
        {  
            string constr = ConfigurationManager.AppSettings["connectionString"];  
            var Client = new MongoClient(constr);  
            var DB = Client.GetDatabase("Employee");  
            var collection = DB.GetCollection<Employee>("EmployeeDetails");  
            var plant = collection.Find(Builders<Employee>.Filter.Where(s => s.Id == id)).FirstOrDefault();  
            return Json(plant);  

        }  
        #endregion  
        #region DeleteEmployee  
        [Route("Delete")]  
        [HttpGet]  
        public object Delete(string id)  
        {  
            try  
            {  
                string constr = ConfigurationManager.AppSettings["connectionString"];  
                var Client = new MongoClient(constr);  
                var DB = Client.GetDatabase("Employee");  
                var collection = DB.GetCollection<Employee>("EmployeeDetails");  
                var DeleteRecored = collection.DeleteOneAsync(  
                               Builders<Employee>.Filter.Eq("Id", id));  
                return new Status  
                { Result = "Success", Message = "Employee Details Delete  Successfully" };  

            }  
            catch (Exception ex)  
            {  
                return new Status  
                { Result = "Error", Message = ex.Message.ToString() };  
            }  

        }  
        #endregion  
    }  
}  

Step 6

Now, let's enable CORS. Go to Tools, open NuGet Package Manager, search for Cors, and install the Microsoft.Asp.Net.WebApi.Cors package.

Installing Microsoft.Asp.Net.Web.Cors package

Open Webapiconfig.cs and add the following lines.

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");    
config.EnableCors(cors);   

Create an Project

Step 1

Create an Angular 7 project with the name "CrudwithMongoDB" by using the following command.

 ng new CrudwithMongoDB

Step 2

Open Visual Studio Code, open the newly created project, and add bootstrap to this project.

npm install bootstrap --save

Step 3

Now, create two components for displaying the employee list page and adding a new employee page. To create the components, open terminal and use the following commands.

ng g c employee
ng g c addemployee

Step 4

Create a class named "employee" by using the following command.

ng g class employee

Add the required properties in the class.

export class Employee {  
    Id: string;  
    Name: string;  
    Department: string;  
    Address: string;  
    City: string;  
    Country: string;  
} 

Step 5

Create a service to call the Web API.

ng g s emprecord

Step 6

Open the emprecord service and import the required packages and classes. Add the following lines of code in the emprecord.service.ts file.

    import { Injectable } from '@angular/core';  
    import { Observable } from "rxjs";  
    import {HttpHeaders, HttpClient } from "@angular/common/http";  
    import { Employee } from "../app/employee";  
    @Injectable({  
      providedIn: 'root'  
    })  
    export class EmprecordService {  
       Url="http://localhost:14026/Api/Employee/";  
      constructor(private http:HttpClient) { }  
       InsertEmployee(employee:Employee)  
       {  
         debugger;  
        const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };  
         return this.http.post<Employee[]>(this.Url+'/InsertEmployee/', employee,httpOptions)  
       }  
       GetEmployeeRecord():Observable<Employee[]>  
       {  
         debugger;  
        return this.http.get<Employee[]>(this.Url+"/GetAllEmployee")  
       }  
       DeleteEmployee(id:string):Observable<number>  
       {  
         debugger;  
        return this.http.get<number>(this.Url + '/Delete/?id='+id);  
       }  
       GetEmployeeById(id:string)  
       {  
        return this.http.get<Employee>(this.Url + '/GetEmployeeById/?id=' + id);  
       }  
       UpdatEmplouee(employee:Employee)  
       {  
        debugger;  
        const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };  
         return this.http.post<Employee[]>(this.Url+'/UpdateEmployee/', employee,httpOptions)  
       }  

    }  

Step 7 - Add Paging and Searching

To add paging and searching, install the following library in the project. For pagination:

npm install --save ngx-pagination  

For searching:

npm i ng2-search-filter --save  

Export and import both these directives in the app.module.ts file.

import {NgxPaginationModule} from 'ngx-pagination';  
import { Ng2SearchPipeModule } from 'ng2-search-filter';  

Step 8

Now, open addemployee.component.html and add the following HTML.


    <div class="container" style="padding-top:40px;">    
      <div class="row">    
        <div class="col-md-10 mx-auto">    
          <div class="card mx-4">   
            <div class="card-head p-4">  
                <div class="col-sm-12 btn btn-success">  
                    Employee's Information  
                  </div>  
            </div>   
            <div class="card-body p-4">    
         <form [formGroup]="Addemployee" (ngSubmit)="onFormSubmit(Addemployee.value)">  
        <div class="col-sm-12">  
          <div class="card-body">  
            <!-- <div class="row"> -->  
            <div class="form-group ">  

              <label class="col-sm-2 control-label" for="Name">Name</label>  
              <div class="col-sm-10">  
                <input type="text" class="form-control" placeholder="Enter name" formControlName="Name">  
              </div>  
            </div>  
            <div class="form-group ">  
              <label class="col-sm-2 control-label" for="Department">Department</label>  
              <div class="col-sm-10">  
                <input type="text" class="form-control" placeholder="Enter Department" formControlName="Department">  
              </div>  
            </div>  
            <div class="form-group ">  
              <label class="col-sm-2 control-label" for="Address">Address</label>  
              <div class="col-sm-10">  
                <input type="text" class="form-control" placeholder="Enter Address" formControlName="Address">  
              </div>  
            </div>  
            <div class="form-group ">  
              <label class="col-sm-2 control-label" for="City">City</label>  
              <div class="col-sm-10">  
                <input type="text" class="form-control" placeholder="Enter City" formControlName="City">  
              </div>  
            </div>  
            <div class="form-group ">  
              <label class="col-sm-2 control-label" for="Country">Country</label>  
              <div class="col-sm-10">  
                <input type="text" class="form-control" placeholder="Enter Country" formControlName="Country">  
              </div>  
            </div>  

          </div>  
        </div>  
        <div class="col-6 text-right">    
            <button class="btn btn-primary px-10" type="submit">Add </button>  
          </div>  
      </form>  
          </div>    
        </div>    
      </div>    
      </div>   
    </div>   

Step 9

Open the addemployee.componet.ts file and add the following lines.

    import { Component, OnInit } from '@angular/core';  
    import { HttpClient } from "@angular/common/http";  
    import { FormGroup, FormControl } from '@angular/forms';  
    import { EmprecordService } from "../../emprecord.service";  
    import { Employee } from "../../employee";  
    import { Observable } from "rxjs";  
    import { identifierModuleUrl } from '@angular/compiler';  
    import { Router } from '@angular/router';  
    @Component({  
      selector: 'app-addemployee',  
      templateUrl: './addemployee.component.html',  
      styleUrls: ['./addemployee.component.css']  
    })  
    export class AddemployeeComponent implements OnInit {  
      massage: string;  
      dataSaved = false;  
      Addemployee:FormGroup;  
      EmployeeIdUpdate = "0";  
      constructor(private router: Router,private emprecordService:EmprecordService) { }  

      InsertEmployee(employee:Employee)  
      {  
    debugger;  
        if (this.EmployeeIdUpdate != "0") employee.Id=this.EmployeeIdUpdate;  
          this.emprecordService.InsertEmployee(employee).subscribe(  
            ()=>  
            {  
              if (this.EmployeeIdUpdate == "0") {  
                this.massage = 'Saved Successfully';  

              }  
              else  
              {  
                this.massage = 'Update Successfully';  
              }  
              this.dataSaved = true;  
              this.router.navigate(['/employee']);  
            })  
      }  
      onFormSubmit() {  
        const Emp = this.Addemployee.value;  
        this.InsertEmployee(Emp);  
      }  

      EmployeeEdit(id: string) {  
        debugger;  
        this.emprecordService.GetEmployeeById(id).subscribe(emp => {  
          this.massage = null;  
          this.dataSaved = false;  
          debugger;  
          this.EmployeeIdUpdate=id;  
          this.Addemployee.controls['Name'].setValue(emp.Name);  
          this.Addemployee.controls['Department'].setValue(emp.Department);  
          this.Addemployee.controls['City'].setValue(emp.City);  
          this.Addemployee.controls['Country'].setValue(emp.Country);  
          this.Addemployee.controls['Address'].setValue(emp.Address);  
        });  
        debugger;  
      }  
      clearform() {  
        debugger;  
        this.Addemployee.controls['Name'].setValue("");  
        this.Addemployee.controls['Department'].setValue("");  
        this.Addemployee.controls['Address'].setValue("");  
        this.Addemployee.controls['City'].setValue("");  
        this.Addemployee.controls['Country'].setValue("");  

      }  
      ngOnInit() {  
        this.Addemployee = new FormGroup({  

          Name: new FormControl(),  
          Department:new FormControl(),  
          Address:new FormControl(),  
          City:new FormControl(),  
          Country:new FormControl(),  
      });  
      let Id = localStorage.getItem("id");  
    if(Id!=null)  
    {  
      this.EmployeeEdit(Id) ;  
     }}  
    }  

Step 10

Open employee.componet.html and add this HTML.


    <div class="container" style="margin-bottom:20px;padding-top:20px;">  
      <div class="row">  
        <div class="col-sm-12 btn btn-success">  
          Employee's Information  
        </div>  
      </div>  
      <div class="col-sm-12" style="margin-bottom:20px;padding-top:20px;">  
        <div class="row">  
          <div class="col-sm-6">  
            <button type="button" class="btn btn-primary" data-toggle="modal" routerLink="/addemployee">  
              Add New Employee  
            </button>  
          </div>  
          <div class="col-sm-6">  
            <input class="form-control" type="text" name="search" [(ngModel)]="filter" placeholder="Search">  
          </div>  
        </div>  
      </div>  
    </div>  
    <div class="container" style="padding-top:20px;">  
      <table class="table table-striped">  
        <thead class="thead-dark">  
          <th>Name</th>  
          <th>Department</th>  
          <th>Address</th>  
          <th>City</th>  
          <th>Country</th>  
          <th>Action</th>  
        </thead>  
        <tbody>  
          <tr *ngFor="let e of emp | async|filter:filter| paginate: { itemsPerPage: 5, currentPage: p } ; let i=index">  
            <td>{{e.Name}}</td>  
            <td>{{e.Department}}</td>  
            <td>{{e.Address}}</td>  
            <td>{{e.City}}</td>  
            <td>{{e.Country}}</td>  
            <td>  
              <div class="btn-group">  
                <button type="button" class="btn btn-primary mr-1" (click)="EmployeeEdit(e.Id)">Edit</button>  
                <button type="button" class="btn btn-danger mr-1" (click)="Deleteemployee(e.Id)">Delete</button>  
              </div>  
            </td>  
          </tr>  
        </tbody>  
      </table>  
      <ul class="pagination">  
        <pagination-controls (pageChange)="p = $event"></pagination-controls>  
      </ul>  
    </div>  

Step 11

Open employee.componet.ts file and add the following lines.

    import { Component, OnInit } from '@angular/core';  
    import { Employee } from "../employee";  
    import { EmprecordService } from "../emprecord.service";  
    import { Observable } from "rxjs";  
    import { Router } from '@angular/router';  
    @Component({  
      selector: 'app-employee',  
      templateUrl: './employee.component.html',  
      styleUrls: ['./employee.component.css']  
    })  
    export class EmployeeComponent implements OnInit {  
      private emp: Observable<Employee[]>;  
      massage:String;  
      dataSaved=false;  
      constructor(private router: Router,private emprecordService:EmprecordService) { }  
       Loademployee()  
       {  
          debugger;  
          this.emp = this.emprecordService.GetEmployeeRecord();  
          console.log(this.emp);  

          debugger;  

       }  
       EmployeeEdit(id: string) {  
        debugger;  
       localStorage.removeItem("id");  
       localStorage.setItem("id",id.toString());  
        this.router.navigate(['/addemployee'], { queryParams: { Id: id } });  
        debugger;  
      }  
       Deleteemployee(id: string) {  
        if (confirm("Are You Sure To Delete this Informations")) {  

          this.emprecordService.DeleteEmployee(id).subscribe(  
            () => {  
              this.dataSaved = true;  
              this.massage = "Deleted Successfully";  
            }  
          );  
        }  
      }  
      ngOnInit() {  
        localStorage.clear();
        this.Loademployee();  

      }  

    }  

Step 12

Now, open app-routing.module.ts file and add the following lines to create routing.

    import { NgModule } from '@angular/core';  
    import { Routes, RouterModule } from '@angular/router';  
    import { EmployeeComponent } from "./employee/employee.component";  
    import { AddemployeeComponent } from "./employee/addemployee/addemployee.component";  

    const routes: Routes = [  
     {path:"employee",component:EmployeeComponent},  
     {path:"addemployee",component:AddemployeeComponent},  
    ];  

    @NgModule({  
      imports: [RouterModule.forRoot(routes)],  
      exports: [RouterModule]  
    })  
    export class AppRoutingModule { }  

Step 13

Now, open app.module.ts file and add the following lines.

import { BrowserModule } from '@angular/platform-browser';  
import { NgModule } from '@angular/core';  
import { FormsModule } from '@angular/forms';  
import { AppRoutingModule } from './app-routing.module';  
import { AppComponent } from './app.component';  
import { HttpClientModule,HttpClient} from '@angular/common/http';   
import { EmployeeComponent } from './employee/employee.component';  
import { ReactiveFormsModule } from "@angular/forms";  
import { EmprecordService } from "../app/emprecord.service";  
import { AddemployeeComponent } from './employee/addemployee/addemployee.component';   
import {NgxPaginationModule} from 'ngx-pagination';   
import { Ng2SearchPipeModule } from 'ng2-search-filter';  

@NgModule({  
  declarations: [  
    AppComponent,  
    EmployeeComponent,  
    AddemployeeComponent,  
  ],  
  imports: [  
    BrowserModule,FormsModule,  
    AppRoutingModule,HttpClientModule,ReactiveFormsModule,Ng2SearchPipeModule,NgxPaginationModule  
  ],  
  providers: [EmprecordService],  
  bootstrap: [AppComponent]  
})  
export class AppModule { }

Step 14

Now, let us run the project and redirect the URL to the Addemployee page.

Employee Information form

Step 15

Enter the details and click on the Add button.

Adding employees

Summary

In this article, we discussed how to perform CRUD operations using MongoDB, Angular 8, and Asp.net Web API.

Angular MongoDB dotnet webdev api

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Top 10 API Security Threats Every API Team Should Know

Learn what are the most important API security threats engineering leaders should be aware of and steps you can take to prevent them

What Are Good Traits That Make Great API Product Managers

What is API product management and what can you be doing to be a better API product manager — get aligned with SaaS and enterprise software requirements. This guide lays out what is API product management and some of the things you should be doing to be a good product manager.

Install Angular - Angular Environment Setup Process

Install Angular in easy step by step process. Firstly Install Node.js & npm, then Install Angular CLI, Create workspace and Deploy your App.

Consume Web API Post method in ASP NET MVC | Calling Web API | Rest API Bangla Tutorial

LIKE | COMMENT | SHARE | SUBSCRIBE In this tutorial, I will discussed about how to consume Web API Get method and display records in the ASP.NET View. Here, ...

Consume Web API Get method in ASP NET MVC | Calling Web API | Rest API Bangla Tutorial

LIKE | COMMENT | SHARE | SUBSCRIBE In this tutorial, I will discussed about How to Consume Web API Get method in ASP NET MVC. Blog : http://aspdotnetexplorer...