CRUD Operation Using Angular And Web API

Introduction

 
In this article, we will try to implement the basic operations ( Create, Read, Update, Delete ) using Angular and WebApi.
 
We will be using the complex object on which all the operations are going to perform.
 
Pre-requisites
 
Before you go ahead you must know some basics of Angular and webapi. Below are some links that are helpful before you start with the article and application implementation.
  1. Getting Started With Angular CLI
  2. Overview Of Components In Angular
  3. HTTP And Observables In Angular
  4. Overview Of Route Parameters In Angular

Implementation

 
Open Visual Studio Code and create the application TestApp.
 
Note
We have used angular CLI commands for generation of Application, Component, services. Also, this is a time-comsuming and long article, go through this only if you have enough time.
 
Eg: for component generation we have used “ng g c addStudent”
 
So you have to keep in mind to generate the components/services/application properly. Or go to my previous angular articles to see the use of angular CLI command.
 
Now create a new application “ng new TestApp”.
 

Modal Creation

 
Create addressClass.ts 
  1. Create export class AddressClass {  
  2.     constructor(  
  3.         public street: string,  
  4.         public city: string,  
  5.         public state: string  
  6.     ){}  
  7. }  
  8. import { AddressClass } from "./addressClass";  
Create studentClass.ts.
  1. import { AddressClass } from "./addressClass";  
  2.   
  3. export class StudentClass {  
  4.     constructor(  
  5.         public id: number,  
  6.         public name: string,  
  7.         public email: string,  
  8.         public phone: number,  
  9.         public gender: string,  
  10.         public course: string,  
  11.         public sendUpdates: boolean,  
  12.         public bloodGroup: string,  
  13.         public address: AddressClass  
  14.     ){}  
  15. }  

Components Creation

 
Let us create some components.
 
Generate component home ( “ng g c home”)
Open home.component.html and edit with below contents, 
  1. <h1>Home page!</h1>  
  2. <p>  
  3.     Students Records Management.  
  4. </p>  
Generate component notFound. ( “ng g c notFound”)
Open not-found.component.html and edit with below contents,
  1. <h2>Not found!</h2>  
  2. <p>The page you are looking for is not available.</p>  
Generate component addStudent. ( “ng g c addStudent”)
 
Open add-student.component.html and edit with the below contents,
  1. <div class="backgroundColor container-fluid" >  
  2.   <h3>  
  3.     Student Registration!  
  4.   </h3>  
  5.   <p>Enter the below fields for student details.</p>  
  6.     <form #studentForm="ngForm" (ngSubmit)="SubmitDetails(studentForm.value)">  
  7.       <div class="row">  
  8.         <div class="col-sm-4">  
  9.           <div class="form-group">  
  10.             <label for="name">Name:</label>  
  11.             <input type="text" #controlName='ngModel' required [class.is-invalid]="controlName.invalid && controlName.touched" class="form-control" [(ngModel)]="studentModel.name" name="name">  
  12.             <small [class.d-none]="controlName.valid || controlName.untouched"  style="color:red">*Field is required</small>  
  13.           </div>  
  14.         </div>  
  15.         <div class="col-sm-4">  
  16.             <div class="form-group">  
  17.                 <label for="email">Email address:</label>  
  18.                 <input type="text" class="form-control" [(ngModel)]="studentModel.email" name="email">  
  19.               </div>  
  20.         </div>  
  21.         <div class="col-sm-4">  
  22.           <div class="form-group">    
  23.             <label for="phone">Phone:</label>    
  24.             <input type="tel" #controlPhone="ngModel" required pattern="^\d{10}$" [class.is-invalid]="controlPhone.invalid && controlPhone.touched" class="form-control" [(ngModel)]="studentModel.phone" name="phone" />    
  25.             <div *ngIf="controlPhone.errors && (controlPhone.invalid && controlPhone.touched)">    
  26.               <small *ngIf="controlPhone.errors.required" class="text-danger">*This field is required</small>    
  27.               <small *ngIf="controlPhone.errors.pattern" class="text-danger">*Must be 10 digit</small>    
  28.             </div>                  
  29.           </div>   
  30.         </div>  
  31.       </div>  
  32.       <div class="row">  
  33.           <div class="col-sm-4">  
  34.               <div class="form-group">  
  35.                   <label for="gender">gender:</label>  
  36.                   <input type="text" class="form-control" [(ngModel)]="studentModel.gender" name="gender">  
  37.                 </div>  
  38.           </div>  
  39.           <div class="col-sm-4">  
  40.               <div class="form-group">  
  41.                   <label for="bloodGroup">Blood Group:</label>  
  42.                   <select required #bloodGroup="ngModel" value="Select" class="form-control" [class.is-invalid]="bloodGroup.invalid && bloodGroup.touched" [(ngModel)]="studentModel.bloodGroup" name="bloodGroup">  
  43.                     <option value="">Select Blood Group</option>  
  44.                     <option *ngFor="let group of groups" >{{group}}</option>  
  45.                   </select>  
  46.                 <small class="text-danger" *ngIf="bloodGroup.invalid && bloodGroup.touched">*Please select Blood group</small>  
  47.                 </div>                
  48.           </div>  
  49.           <div class="col-sm-4">  
  50.               <div class="form-group">  
  51.                 <label>Course </label><br>  
  52.                 <input type="radio" [(ngModel)]="studentModel.course" name="course" value="BCA">BCA     
  53.                 <input type="radio" [(ngModel)]="studentModel.course" name="course" value="B.Tech">B.Tech     
  54.                 <input type="radio" [(ngModel)]="studentModel.course" name="course" value="BE">BE     
  55.                 <input type="radio" [(ngModel)]="studentModel.course" name="course" value="B.Sc">B.Sc     
  56.               </div>  
  57.           </div>          
  58.       </div>  
  59.       <div class="row" ngModelGroup="address">  
  60.           <div class="col-sm-4">  
  61.               <div class="form-group">  
  62.                   <label>Street</label>  
  63.                   <input type="text" class="form-control" name="street" [(ngModel)]="studentModel.address.street">  
  64.                 </div>  
  65.           </div>  
  66.           <div class="col-sm-4">  
  67.               <div class="form-group">  
  68.                   <label>City</label>  
  69.                   <input type="text" class="form-control" name="city" [(ngModel)]="studentModel.address.city">  
  70.                 </div>  
  71.           </div>  
  72.           <div class="col-sm-4">  
  73.               <div class="form-group">  
  74.                   <label>State</label>  
  75.                   <input type="text" class="form-control" name="state" [(ngModel)]="studentModel.address.state">  
  76.                 </div>  
  77.           </div>  
  78.       </div>  
  79.       <div class="checkbox">  
  80.         <label><input type="checkbox" [(ngModel)]="studentModel.sendUpdates" name="sendUpdates"> send me updates</label>  
  81.       </div>  
  82.       <input type="hidden" [(ngModel)]="studentModel.id" name="id">  
  83.       <button type="submit" class="btn btn-primary">Submit</button>  
  84.     </form>   
  85.   </div> 
Open add-student.component.css and edit with below contents,
  1. .backgroundColor  
  2. {  
  3.     background-color:#d5f5f3 !important;  
  4. }  
Open add-student.component.ts and edit with below contents,
  1. import { Component, OnInit } from '@angular/core';  
  2. import { AddressClass } from '../addressClass';  
  3. import { EnrollmentService } from '../enrollment-service.service';  
  4. import { StudentClass } from '../studentClass';  
  5. import { ActivatedRoute, Router } from '@angular/router';  
  6.   
  7. @Component({  
  8.   selector: 'app-add-student',  
  9.   templateUrl: './add-student.component.html',  
  10.   styleUrls: ['./add-student.component.css']  
  11. })  
  12. export class AddStudentComponent implements OnInit {  
  13.   
  14.   groups=['A+''A-''B+''B-''O+''O-'];  
  15.     
  16.   addressModel = new AddressClass("""""");  
  17.   studentModel = new StudentClass(0,""""null""""true""this.addressModel)  
  18.   
  19.   constructor(private _enrollmentService: EnrollmentService, private route: ActivatedRoute, private router : Router) {   
  20.     console.log("constructor calling..");      
  21.     }  
  22.   
  23.   SubmitDetails(studentData){  
  24.     console.log(studentData);  
  25.     if(studentData.id == 0){  
  26.         this._enrollmentService.addStudent(studentData)  
  27.       .subscribe(  
  28.         (data)=>{  
  29.           data => console.log('success', data);  
  30.           this.router.navigate(['/studentList']);  
  31.         },  
  32.         error => console.log('Error', error)  
  33.       );  
  34.     }else  
  35.     {  
  36.         this._enrollmentService.editStudent(studentData)  
  37.       .subscribe(  
  38.         (data)=>{  
  39.           data => console.log('success', data);  
  40.           this.router.navigate(['/studentList']);  
  41.         },  
  42.         error => console.log('Error', error)  
  43.       );  
  44.     }  
  45.       
  46.   }  
  47.      
  48.   ngOnInit() {    
  49.     console.log("ngOnInit method calling..");  
  50.     var id = parseInt(this.route.snapshot.paramMap.get('id'));  
  51.     this._enrollmentService.getStudent(id).subscribe(data => this.studentModel = data);   
  52.   }  
  53. }  
Generate component studentDetails
Open student-details.component.html and edit with the below contents,
  1. <h2>Selected Student Details</h2>  
  2. <h5>This is the details for <b>{{studentModel.name}}</b></h5>  
  3. <div><b>Id: </b>{{studentModel.id}}</div>  
  4. <div><b>Email Address: </b>{{studentModel.email}}</div>  
  5. <div><b>Phone: </b>{{studentModel.phone}}</div>  
  6. <div><b>Gender: </b>{{studentModel.gender}}</div>  
  7. <div><b>Blood group: </b>{{studentModel.bloodGroup}}</div>  
  8. <div><b>Course: </b>{{studentModel.course}}</div>  
  9. <div><b>Street: </b>{{studentModel.address.street}}</div>  
  10. <div><b>City: </b>{{studentModel.address.city}}</div>  
  11. <div><b>State: </b>{{studentModel.address.state}}</div>  
  12. <div><a (click)="gotoStudentList()">Back</a></div> 
Open student-details.component.ts and edit with the below contents,
  1. import { Component, OnInit } from '@angular/core';  
  2. import { ActivatedRoute, Router } from '@angular/router';  
  3. import { StudentClass } from '../studentClass';  
  4. import { EnrollmentService } from '../enrollment-service.service';  
  5.   
  6. @Component({  
  7.   selector: 'app-student-details',  
  8.   templateUrl: './student-details.component.html',  
  9.   styleUrls: ['./student-details.component.css']  
  10. })  
  11. export class StudentDetailsComponent implements OnInit {  
  12.   
  13.   studentModel : StudentClass;  
  14.   constructor(private _enrollmentService: EnrollmentService, private route : ActivatedRoute, private router : Router) {   
  15.   }  
  16.   
  17.   ngOnInit() {  
  18.     var id = parseInt(this.route.snapshot.paramMap.get('id'));  
  19.     this._enrollmentService.getStudent(id).subscribe(data => this.studentModel = data);   
  20.   }  
  21.   
  22.   gotoStudentList(){  
  23.     this.router.navigate(['/studentList']);   
  24.   }  
  25.   
  26.   showFees(){  
  27.     this.router.navigate(['fees'], {relativeTo: this.route});  
  28.   }  
  29.   
  30.   showAddress(){  
  31.     this.router.navigate(['address'], {relativeTo: this.route});  
  32.   }  
  33. }  
Generate studentList component
 
Open student-list.component.html and edit with the below contents,
  1. <h2>Student Details:</h2>    
  2. <table class="table">  
  3.     <thead>  
  4.         <tr><th>Id</th><th>Name</th><th>Action</th></tr>  
  5.     </thead>  
  6.     <tbody>  
  7.         <tr *ngFor="let stud of students, index as i">  
  8.             <td>  
  9.                 <a routerLink="/student-list/{{stud.name}}/{{stud.phone}}/{{stud.email}}"> {{stud.name}}</a>  
  10.             </td>  
  11.             <td>  
  12.                 <a routerLink="/student-list/{{stud.name}}/{{stud.phone}}/{{stud.email}}"> {{stud.phone}} </a>  
  13.             </td>  
  14.             <td>  
  15.                 <a (click)=deleteStudent(stud.id,i)>| Delete |</a>  
  16.                 <a (click)=editStudent(stud)> Edit |</a>  
  17.                 <a (click)=studentDetails(stud)> View |</a>  
  18.             </td>  
  19.         </tr>  
  20.     </tbody>     
  21. </table>  
Open student-list.component.ts and edit with the below contents,
  1. import { Component, OnInit } from '@angular/core';  
  2. import { EnrollmentService } from '../enrollment-service.service';  
  3. import { Router, Route } from '@angular/router';  
  4.   
  5. @Component({  
  6.   selector: 'app-student-list',  
  7.   templateUrl: './student-list.component.html',  
  8.   styleUrls: ['./student-list.component.css']  
  9. })  
  10. export class StudentListComponent implements OnInit {  
  11.   
  12.   public students: any[];   
  13.   
  14.   constructor(private _enrollmentService: EnrollmentService, private router : Router) {   
  15.     console.log("constructor calling..");      
  16.     }   
  17.   getAllStudents(){  
  18.     this._enrollmentService.getAllStudents().subscribe(  
  19.       data => this.students = data,  
  20.       error => console.log('Error in getting stud list'),  
  21.         () => {console.log('success to update stud list...');  
  22.       });   
  23.   }  
  24.   public deleteStudent(id, index)  
  25.    {  
  26.       this._enrollmentService.deleteStudent(id)  
  27.       .subscribe(  
  28.         ()=>{  
  29.           data => console.log('success', data);  
  30.           this.students.splice(index,1);  
  31.         },  
  32.         error => console.log('Error', error)  
  33.       );  
  34.    }  
  35.    editStudent(student)  
  36.    {  
  37.     this.router.navigate(['/addStudent', student.id]);   
  38.    }  
  39.    studentDetails(id)  
  40.    {  
  41.     this.router.navigate(['/studentDetails', id]);   
  42.    }  
  43.      
  44.   ngOnInit() {    
  45.     console.log("ngOnInit method calling..");  
  46.     this.getAllStudents();  
  47.   }  
  48. }  
Create Routing file app-routing.module.ts and edit with the below contents,
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { StudentDetailsComponent } from './student-details/student-details.component';  
  4. import { StudentMarksComponent } from './student-marks/student-marks.component';  
  5. import { NotFoundComponent } from './not-found/not-found.component';  
  6. import { StudentListComponent } from './student-list/student-list.component';  
  7. import { StudentFeesComponent } from './student-fees/student-fees.component';  
  8. import { StudentAddressComponent } from './student-address/student-address.component';  
  9. import { AddStudentComponent } from './add-student/add-student.component';  
  10. import { HomeComponent } from './home/home.component';  
  11.   
  12. const routes:Routes = [  
  13.     {path: 'home', component: HomeComponent},  
  14.     {path: 'addStudent', component : AddStudentComponent},    
  15.     {path: 'addStudent/:id', component : AddStudentComponent},    
  16.     {path: 'studentList', component : StudentListComponent},  
  17.     {path: '', redirectTo : '/student-list', pathMatch : 'full'},  
  18.     {path: 'student-list', component : StudentListComponent},  
  19.     {path: 'student-list/:id/:name/:marks', component : StudentDetailsComponent,  
  20.         children : [  
  21.             {path: 'fees', component : StudentFeesComponent},  
  22.             {path: 'address', component : StudentAddressComponent}  
  23.         ]},  
  24.     {path: 'studentMarks', component : StudentMarksComponent},  
  25.     {path: 'studentDetails', component : StudentDetailsComponent},  
  26.     {path: "**", component : NotFoundComponent}  
  27. ];  
  28.   
  29. @NgModule({  
  30.     imports : [RouterModule.forRoot(routes)],  
  31.     exports: [RouterModule]  
  32. })  
  33. export class AppRoutingModule{}  
Generate service enrollmentService and edit with the below contents.
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';    
  3. import { Observable } from 'rxjs';  
  4. import { StudentClass } from './studentClass';  
  5.   
  6. @Injectable({  
  7.   providedIn: 'root'  
  8. })  
  9. export class EnrollmentService {  
  10.   
  11.   _url = 'https://localhost:44302/Api/Student/';// may be different in your system, so change accorringly  
  12.   constructor(private _http: HttpClient) { }  
  13.   
  14.   addStudent(student: StudentClass){  
  15.     return this._http.post<any>(this._url + 'AddStudent', student)  
  16.   }  
  17.   editStudent(student: StudentClass){  
  18.     return this._http.put<any>(this._url + 'EditStudent', student)  
  19.   }  
  20.   deleteStudent(id: number){  
  21.     return this._http.delete<any>(this._url + 'DeleteStudent?id=' + id);  
  22.   }  
  23.   getAllStudents(): Observable<any[]> {    
  24.     return this._http.get<any[]>(this._url+'AllStudentsDetails');    
  25.   }  
  26.   getStudent(id: number): Observable<any> {    
  27.     return this._http.get<any[]>(this._url+'GetStudent?id=' + id);    
  28.   }  
  29. }  
Open app.component.html and edit with the below contents,
  1. <nav class="navbar navbar-default" style="background-color: #323b38;">  
  2.   <div class="container-fluid">  
  3.     <div class="navbar-header">  
  4.       <a class="navbar-brand text-color-white" href="#">Student Record Management.</a>  
  5.     </div>  
  6.     <ul class="nav navbar-nav">  
  7.       <li><a routerLink="/home" class="text-color-white">Home</a></li>  
  8.       <li>  
  9.         <a routerLink="/addStudent" class="text-color-white">Add Student</a>  
  10.       </li>  
  11.       <li>  
  12.         <a routerLink="/studentList" class="text-color-white">List Student</a>  
  13.       </li>  
  14.     </ul>  
  15.   </div>  
  16. </nav>  
  17. <div style="margin-left:2%; margin-top:1.5%; margin-right: 5%;">  
  18.   <router-outlet></router-outlet>  
  19. </div>  
Open app.compnent.css and edit with the below contents,
  1. .text-color-white  
  2. {  
  3.  color: #f7faf9 !important;  
  4. }  
Open app.module.ts and make sure to add the dependencies,
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { AppComponent } from './app.component';  
  5. import { StudentDetailsComponent } from './student-details/student-details.component';  
  6. import { StudentMarksComponent } from './student-marks/student-marks.component';  
  7. import { AppRoutingModule } from './app-routing.module';  
  8. import { NotFoundComponent } from './not-found/not-found.component';  
  9. import { StudentComponent } from './student/student.component';  
  10. import { StudentListComponent } from './student-list/student-list.component';  
  11. import { StudentAddressComponent } from './student-address/student-address.component';  
  12. import { StudentFeesComponent } from './student-fees/student-fees.component';  
  13. import { AddStudentComponent } from './add-student/add-student.component';  
  14. import { EnrollmentService } from './enrollment-service.service';  
  15. import { HttpClientModule,HttpClient } from '@angular/common/http';  
  16. import { HomeComponent } from './home/home.component';    
  17.   
  18. @NgModule({  
  19.   declarations: [  
  20.     AppComponent,  
  21.     StudentDetailsComponent,  
  22.     StudentMarksComponent,  
  23.     NotFoundComponent,  
  24.     StudentComponent,  
  25.     StudentListComponent,  
  26.     StudentAddressComponent,  
  27.     StudentFeesComponent,  
  28.     AddStudentComponent,  
  29.     HomeComponent  
  30.   ],  
  31.   imports: [  
  32.     BrowserModule,  
  33.     FormsModule,  
  34.     AppRoutingModule,  
  35.     HttpClientModule      
  36.   ],  
  37.   providers: [HttpClientModule,EnrollmentService],  
  38.   bootstrap: [AppComponent]  
  39. })  
  40. export class AppModule { }  
Open Microsoft SQL server Management studio and create a database StudentDB and create a table student.
  1. USE [StudentDB]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[student]    Script Date: 12-10-2019 12:12:31 ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. CREATE TABLE [dbo].[student](  
  12.     [id] [int] IDENTITY(1,1) NOT NULL,  
  13.     [name] [varchar](50) NULL,  
  14.     [email] [varchar](50) NULL,  
  15.     [phone] [varchar](50) NULL,  
  16.     [gender] [varchar](10) NULL,  
  17.     [course] [varchar](10) NULL,  
  18.     [sendUpdates] [bitNULL,  
  19.     [street] [varchar](50) NULL,  
  20.     [city] [varchar](50) NULL,  
  21.     [state] [varchar](50) NULL  
  22. ON [PRIMARY]  
  23. GO  
Open Visual Studio and create a web Api project and give it a name StudentApi.
 
Create folder Model and add modals as below, 
  1. namespace StudentApi.Models  
  2. {  
  3.     public class AddressClass  
  4.     {  
  5.         public string street { getset; }  
  6.         public string city { getset; }  
  7.         public string state { getset; }  
  8.     }  
  9. }  
  10.   
  11. namespace StudentApi.Models  
  12. {  
  13.     public class StudentClass  
  14.     {  
  15.         public int id { getset; }  
  16.         public string name { getset; }  
  17.         public string email { getset; }  
  18.         public string phone { getset; }  
  19.         public string gender{get;set;}  
  20.         public string course{get;set;}  
  21.         public bool sendUpdates { getset; }  
  22.         public string bloodGroup {get;set;}  
  23.         public AddressClass address { getset; }  
  24.     }  
  25. }  
Create a controller Student and edit with the below contents,
  1. using StudentApi.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Data.SqlClient;  
  5. using System.Web.Http;  
  6. using System.Web.Http.Results;  
  7.   
  8. namespace StudentApi.Controllers  
  9. {  
  10.     [RoutePrefix("Api/Student")]  
  11.     public class StudentController : ApiController  
  12.     {  
  13. // configure connection string according to your system  
  14.         SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-M3EM8R3\MSSQLSERVER01;Initial Catalog=StudentDB;Integrated Security=True");  
  15.         SqlCommand cmd;  
  16.         SqlDataAdapter adapt;  
  17.         [HttpGet]  
  18.         [Route("AllStudentsDetails")]  
  19.         public JsonResult<List<Models.StudentClass>> GetAllStudents()  
  20.         {  
  21.             SqlCommand cmd = new SqlCommand();  
  22.             var studList = new List<StudentClass>();  
  23.             cmd.Connection = con;  
  24.             cmd.Connection.Open();  
  25.             cmd.CommandText = "Select * from student";  
  26.             SqlDataReader dr = cmd.ExecuteReader();  
  27.             while (dr.Read())  
  28.             {  
  29.                 studList.Add( new StudentClass  
  30.                 {  
  31.                     id = Convert.ToInt32(dr.GetValue(0)),  
  32.                     name = dr.GetValue(1).ToString(),  
  33.                     email = dr.GetValue(2).ToString(),  
  34.                     phone = dr.GetValue(3).ToString(),  
  35.                     gender = dr.GetValue(4).ToString(),  
  36.                     course = dr.GetValue(5).ToString(),  
  37.                     sendUpdates = Convert.ToBoolean(dr.GetValue(6).ToString()),  
  38.                     address = new AddressClass  
  39.                     {  
  40.                         street = dr.GetValue(7).ToString(),  
  41.                         city = dr.GetValue(8).ToString(),  
  42.                         state = dr.GetValue(9).ToString()  
  43.                     }  
  44.                 });  
  45.   
  46.             }  
  47.             return Json<List<Models.StudentClass>>(studList);  
  48.         }  
  49.         [HttpGet]  
  50.         [Route("GetStudent")]  
  51.         public JsonResult<Models.StudentClass> GetStudent(int id)  
  52.         {  
  53.             SqlCommand cmd = new SqlCommand();  
  54.             cmd.Connection = con;  
  55.             cmd.Connection.Open();  
  56.             cmd.CommandText = "Select * from student where id="+id;  
  57.             SqlDataReader dr = cmd.ExecuteReader();  
  58.             if (dr.HasRows)  
  59.             {  
  60.                 dr.Read();  
  61.                 var stud = new StudentClass  
  62.                 {  
  63.                     id = Convert.ToInt32(dr.GetValue(0)),  
  64.                     name = dr.GetValue(1).ToString(),  
  65.                     email = dr.GetValue(2).ToString(),  
  66.                     phone = dr.GetValue(3).ToString(),  
  67.                     gender = dr.GetValue(4).ToString(),  
  68.                     course = dr.GetValue(5).ToString(),  
  69.                     sendUpdates = Convert.ToBoolean(dr.GetValue(6).ToString()),  
  70.                     address = new AddressClass  
  71.                     {  
  72.                         street = dr.GetValue(7).ToString(),  
  73.                         city = dr.GetValue(8).ToString(),  
  74.                         state = dr.GetValue(9).ToString()  
  75.                     }  
  76.                 };  
  77.                 return Json(stud);  
  78.             }                  
  79.             return null;  
  80.         }  
  81.         [HttpPost]  
  82.         [Route("AddStudent")]  
  83.         public bool InsertStudent(Models.StudentClass student)  
  84.         {  
  85.             con.Open();  
  86.             cmd = new SqlCommand("insert into student(name, email, phone, gender, course, sendUpdates, street, city, state) values('"+student.name+ "', '" + student.email + "', '" + student.phone + "', '" + student.gender + "', '" + student.course + "', " + Convert.ToInt16(student.sendUpdates) + ", '" + student.address.street + "', '" + student.address.city + "', '" + student.address.state + "')", con);  
  87.             int x = cmd.ExecuteNonQuery();  
  88.             con.Close();  
  89.             bool status = x ==1 ? true : false;   
  90.             return status;  
  91.         }  
  92.         [HttpPut]  
  93.         [Route("EditStudent")]  
  94.         public bool UpdateStudent(Models.StudentClass student)  
  95.         {  
  96.             con.Open();  
  97.             cmd = new SqlCommand("update student set " +  
  98.                 "name = '" + student.name + "'," +  
  99.                 " email = '" + student.email + "'," +  
  100.                 " phone = '" + student.phone + "'," +  
  101.                 " gender = '" + student.gender + "'," +  
  102.                 " course = '" + student.course + "'," +  
  103.                 " sendUpdates = " + Convert.ToInt16(student.sendUpdates) + "," +  
  104.                 " street = '" + student.address.street + "'," +  
  105.                 " city = '" + student.address.city + "'," +  
  106.                 " state = '" + student.address.state + "'" +  
  107.                 " where id = " + student.id, con);  
  108.             int x = cmd.ExecuteNonQuery();  
  109.             con.Close();  
  110.             bool status = x == 1 ? true : false;  
  111.             return status;  
  112.         }  
  113.         [HttpDelete]  
  114.         [Route("DeleteStudent")]  
  115.         public bool DeleteStudent(int id)  
  116.         {  
  117.             con.Open();  
  118.             cmd = new SqlCommand("delete from student where id="+id, con);  
  119.             int x = cmd.ExecuteNonQuery();  
  120.             con.Close();  
  121.             bool status = x == 1 ? true : false;  
  122.             return status;  
  123.         }  
  124.     }  
  125. }  
Run the application,
 
CRUD Operation Using Angular And Web API
 
Click on Add Student.
 
CRUD Operation Using Angular And Web API
 
Click on List Student.
 
CRUD Operation Using Angular And Web API
 
Clicking on Delete will delete the record and Clicking on Edit will open the Add Stduent page with filled details.
 
Click on View of any record.
 
CRUD Operation Using Angular And Web API
 
Thank you soo much for going through this article. I hope you enjoyed it and found this article good enough for your learning. Keep continuing your learning and sharing.