Click here to Skip to main content
15,878,852 members
Articles / Web Development / HTML

Angular 4 Insert, Update, Delete with ASP.NET WEB API

Rate me:
Please Sign up or sign in to vote.
4.27/5 (7 votes)
20 Sep 2018CPOL4 min read 44.5K   1.1K   9   6
Angular 4 Insert, Update, Delete with ASP.NET WEB API

Introduction

Angular 4 is more popular nowadays and for beginners, I will tell you what’s new in Angular 4 and show you a practical example of Angular 4 with ASP.NET Web API for inserting, deleting and displaying data using Angular 4.

Basically, this article will demonstrate with example the following:

  • Step by step procedure to create ASP.NET Web API project
  • Prerequisites and Setup for Angular 4
  • How to create Angular 4 Application and install Angular 4 packages
  • How to create service and component in Angular 4
  • How to get data from server side (Web API)
  • How to bind/Load/Fill data from Server side to HTML page using Angular 4
  • How to perform insert, edit, update and delete operation on view using Angular 4 data binding

What is Angular

Angular is an Open Source which is developed by Google.

Angular 4 is the latest version of Angular. It is a front-end web application platform.

What’s New in Angular 4

  1. Reduced Size and Improved Performance
  2. Separate Animation Package
  3. ngIf with else: We can use an else syntax in your templates
  4. As: Introduced as new keyword, As Keywprd allows to store a result in a variable of the template, to use it in the element
  5. Titlecase: Angular 4 introduced a new titlecase pipe. This pipe converts the first letter of each word into uppercase
  6. Http: Adding search parameters to an HTTP request has been simplified
  7. Validators: Added new validators like required, minLength, maxLength and pattern. Email validator helps you validate that the input is a valid email

What You Need

  • Basic knowledge of Angular
  • Angular CLI

Prerequisites

  • Node
  • Npm
  • Angular CLI
  • Typescript
  • Text editor- visual code

Install the below setup step by step, Using Visual Studio Code or Command Prompt

  • Node
  • Npm
  • Angular CLI
  • Typescript
  • Visual code

Set Up for Angular 4

Verify Version of Node

  • node -v
  • npm –v

Installing Angular CLI

npm install -g @angular/cli

Typescript Installation

First, check typescript version using the below command:

tsc –version

If Typescript is not installed, then use command:

npm install –g typescript

Step 1: Start With ASP.NET Web API

  1. Create Database WebAPIDB with the below structure:
    SQL
    CREATE TABLE [dbo].[Employee] (
        [EmployeeID] INT          IDENTITY (1, 1) NOT NULL,
        [FirstName]  VARCHAR (50) NULL,
        [LastName]   VARCHAR (50) NULL,
        [EmpCode]    VARCHAR (50) NULL,
        [Position]   VARCHAR (50) NULL,
        [Office]     VARCHAR (50) NULL,
        CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([EmployeeID] ASC)
    );
  2. Generate Entity Model from Database Name as DBModel.edmx:
  3. Add Web API Controller:
    JavaScript
    public class EmployeeController : ApiController
       {
           private MyDBEntities db = new MyDBEntities(); 
           public IQueryable<Employee> GetEmployees()
           {
               return db.Employees;
           } 
           public IHttpActionResult PutEmployee(int id, Employee employee)
           { 
               if (id != employee.EmployeeID)
               {
                   return BadRequest();
               } 
               db.Entry(employee).State = EntityState.Modified;
    
               try
               {
                   db.SaveChanges();
               }
               catch (DbUpdateConcurrencyException)
               {
                   if (!EmployeeExists(id))
                   {
                       return NotFound();
                   }
                   else
                   {
                       throw;
                   }
               } 
               return StatusCode(HttpStatusCode.NoContent);
           } 
           [ResponseType(typeof(Employee))]
           public IHttpActionResult PostEmployee(Employee employee)
           {
               db.Employees.Add(employee);
               db.SaveChanges(); 
               return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeID }, employee);
           }
    
           [ResponseType(typeof(Employee))]
           public IHttpActionResult DeleteEmployee(int id)
           {
               Employee employee = db.Employees.Find(id);
               if (employee == null)
               {
                   return NotFound();
               } 
               db.Employees.Remove(employee);
               db.SaveChanges(); 
               return Ok(employee);
           }
    
           protected override void Dispose(bool disposing)
           {
               if (disposing)
               {
                   db.Dispose();
               }
               base.Dispose(disposing);
           }
    
           private bool EmployeeExists(int id)
           {
               return db.Employees.Count(e => e.EmployeeID == id) > 0;
           }
       }  

    In the above class, we have the following methods:

    1. GetEmployee() method will return all the employees in JSON format
    2. PostEmployee() method will add a new employee to the database
    3. DeleteEmployee() method will delete existing employee
  4. Install Swagger Package Swashbuckle

    Test Web API using Swagger:

Step 2: Start With Angular 4

Step 1

Create a folder of the name EmployeeApplication. Open Visual Studio code and open this folder in it. This folder will be used as the workspace for creating all the required files for the application.

Creating new Angular projects is easy by using Angular CLI in the following way:

Go To View -- > Integrated Terminal

Cd EmployeeApplication  
$ ng new EmployeeApplication  

Run the following command from the command prompt.

npm install

To serve the app locally, inside your newly created project, run the following command:

ng serve

Open Chrome and add address http://localhost:4200/

Create New Employee Service using the below command:

ng generate service Employee

EmployeeService.js file is used for calling server-side code by using .$http in EmployeeService.js file we have created an Angular service called as EmployeeService. To call Web API EmployeeControllers for insert, update, delete function, we have created three functions in EmployeeService.js.

We have created the following method in service to call Server Side code:

  1. postEmployee(): This will post data to server
  2. getEmployeeList(): This will fetch data from server
  3. deleteEmployee(): This will delete employee from server
JavaScript
export class EmployeeService {
  selectedEmployee : Employee;
  employeeList : Employee[];
  constructor(private http : Http) { }

  postEmployee(emp : Employee){
    var body = JSON.stringify(emp);
    var headerOptions = new Headers({'Content-Type':'application/json'});
    var requestOptions = new RequestOptions({method : RequestMethod.Post,headers : headerOptions});
    return this.http.post('http://localhost:28750/api/Employee',body,requestOptions).map(x => x.json());
  }

  putEmployee(id, emp) {
    var body = JSON.stringify(emp);
    var headerOptions = new Headers({ 'Content-Type': 'application/json' });
    var requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
    return this.http.put('http://localhost:28750/api/Employee/' + id,
      body,
      requestOptions).map(res => res.json());
  }
  getEmployeeList(){
    this.http.get('http://localhost:28750/api/Employee')
    .map((data : Response) =>{
      return data.json() as Employee[];
    }).toPromise().then(x => {
      this.employeeList = x;
    })
  }
  deleteEmployee(id: number) {
    return this.http.delete('http://localhost:28750/api/Employee/' + id).map(res => res.json());
  }
}

A component in Angular:

A major part of the development with Angular 4 is done in the components.

In Angular application, Components are basically classes that interact with the .html file of the component.

It consists of:

  1. Template
  2. Class
  3. Metadata

We will get all details of the component using the below link:

Create New Employee Component using the below command:

ng generate component Employee
JavaScript
export class EmployeeComponent implements OnInit {

  constructor(private employeeService: EmployeeService, private toastr: ToastrService) { }

  ngOnInit() {
    this.resetForm();
  }

  resetForm(form?: NgForm) {
    if (form != null)
      form.reset();
    this.employeeService.selectedEmployee = {
      EmployeeID: null,
      FirstName: '',
      LastName: '',
      EmpCode: '',
      Position: '',
      Office: ''
    }
  }

  onSubmit(form: NgForm) {
    if (form.value.EmployeeID == null) {
      this.employeeService.postEmployee(form.value)
        .subscribe(data => {
          this.resetForm(form);
          this.employeeService.getEmployeeList();
          this.toastr.success('New Record Added Successfully', 'Employee Register');
        })
    }
    else {
      this.employeeService.putEmployee(form.value.EmployeeID, form.value)
      .subscribe(data => {
        this.resetForm(form);
        this.employeeService.getEmployeeList();
        this.toastr.info('Record Updated Successfully!', 'Employee Register');
      });
    }
  }
}

Add another component for List:

ng generate component EmployeeList

We are using ToasterService for showing notification on UI.

This component is used for showing employing list. It will fetch data from Web API and will show on UI.

JavaScript
export class EmployeeListComponent implements OnInit {

  constructor(private employeeService: EmployeeService,private toastr : ToastrService) { }

  ngOnInit() {
    this.employeeService.getEmployeeList();
  }

  showForEdit(emp: Employee) {
    this.employeeService.selectedEmployee = Object.assign({}, emp);;
  }

  onDelete(id: number) {
    if (confirm('Are you sure to delete this record ?') == true) {
      this.employeeService.deleteEmployee(id)
      .subscribe(x => {
        this.employeeService.getEmployeeList();
        this.toastr.warning("Deleted Successfully","Employee Register");
      })
    }
  }
}

We are using the below attributes:

  1. The ng-model attribute is used for Binding controls such as input, text area and selects in the view into the model
  2. ng-submit: The ng-submit directive submits a form to a specified function
  3. ngModel: The ng-model attribute is used to bind the data in your model to the view presented to the user.

Add the below UI to employee.component.html file:

HTML
<form class="emp-form" 
#employeeForm="ngForm" (ngSubmit)="onSubmit(employeeForm)">
  <input type="hidden" name="EmployeeID" #EmployeeID="ngModel" 
    [(ngModel)]="employeeService.selectedEmployee.EmployeeID">
  <div class="form-row">
    <div class="form-group col-md-6">
      <input class="form-control" name="FirstName" #FirstName="ngModel" 
           [(ngModel)]="employeeService.selectedEmployee.FirstName"
        placeholder="First Name" required>
      <div class="validation-error" *ngIf="FirstName.invalid && FirstName.touched">
       This Field is Required.</div>
    </div>
    <div class="form-group col-md-6">
      <input class="form-control" name="LastName" #LastName="ngModel" 
         [(ngModel)]="employeeService.selectedEmployee.LastName" placeholder="Last Name"
        required>
      <div class="validation-error" *ngIf="LastName.invalid && LastName.touched">
       This Field is Required.</div>
    </div>
  </div>
  <div class="form-group">
    <input class="form-control" name="Position" #Position="ngModel" 
    [(ngModel)]="employeeService.selectedEmployee.Position" placeholder="Position">
  </div>
  <div class="form-row">
    <div class="form-group col-md-6">
      <input class="form-control" name="EmpCode" #EmpCode="ngModel" 
       [(ngModel)]="employeeService.selectedEmployee.EmpCode" placeholder="Emp Code">
    </div>
    <div class="form-group col-md-6">
      <input class="form-control" name="Office" #Office="ngModel" 
       [(ngModel)]="employeeService.selectedEmployee.Office" placeholder="Office">
    </div>
  </div>
  <div class="form-row">
    <div class="form-group col-md-8">
      <button [disabled]="!employeeForm.valid" 
      type="submit" class="btn btn-lg btn-block btn-info">
        <i class="fa fa-floppy-o"></i> Submit</button>
    </div>
    <div class="form-group col-md-4">
      <button type="button" class="btn btn-lg btn-block btn-secondary" 
      (click)="resetForm(employeeForm)">
        <i class="fa fa-repeat"></i> Reset</button>
    </div>
  </div>
</form>

Add command Ng Serve to test your application.

NPM Start

Open Chrome and add address http://localhost:4200/

By using this, you have successfully inserted data in the database and you have also shown this in the gridview. Click on submit.

Please take a look at the attached code for more information.

Happy programming!!

Don’t forget to leave your feedback and comments below!

License

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


Written By
Technical Lead
India India
Sujit Bhujbal is Senior Software Engineer having over 12 + years of Experience in .NET core , C#, Angular , SQL Server and has worked on various platforms. He worked during various phases of SDLC such as Requirements and Analysis, Design and Construction, development, maintenance, Testing, UAT.

He is Microsoft Certified Technology Specialist (MCTS) in Asp.net /WCF Applications. He worked at various levels and currently working as a Senior Software Engineer.

His core areas of skill are Web application development using WPF,WCF , C#.Net, ASP.Net 3.5, WCF, SQL Server 2008, CSS, Java script Web design using HTML, AJAX and Crystal Reports

He is proficient in developing applications using SilverLight irrespective of the language, with sound knowledge of Microsoft Expression Blend and exposure to other Microsoft Expression studio tools.


Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

------------------------------------------------------------------------
Blog: Visit Sujit Bhujbal

CodeProject:- Sujit Bhujbal codeproject

DotNetHeaven:- DotNetHeaven

CsharpCorner:-CsharpCorner

Linkedin :-Linkedin

Stack-Exchange: <a href="http://stackexchange.com/users/469811/sujit-bhu

Comments and Discussions

 
QuestionAngular version Pin
markchagers21-Sep-18 2:41
markchagers21-Sep-18 2:41 
I'm somewhat surprised to read in your article that Angular is currently at version 4 when version 6 has been out for some time now. see Angular Docs[^]. You might want to update your article.
AnswerRe: Angular version Pin
Sujeet Bhujbal22-Sep-18 7:19
Sujeet Bhujbal22-Sep-18 7:19 
GeneralRe: Angular version Pin
markchagers23-Sep-18 20:35
markchagers23-Sep-18 20:35 
GeneralRe: Angular version Pin
brianlowe25-Sep-18 2:16
brianlowe25-Sep-18 2:16 
QuestionInformative Pin
Edith1220-Sep-18 1:50
professionalEdith1220-Sep-18 1:50 
AnswerRe: Informative Pin
Sujeet Bhujbal20-Sep-18 19:48
Sujeet Bhujbal20-Sep-18 19:48 

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.