Monday 4 March 2019

CRUD operation using webapi2, angular6 & ngx-bootstrap modal & datepicker




Web api :

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication5.Models;

namespace WebApplication5.Controllers
{
    [RoutePrefix("api/Pgs")]
    public class PgsController : ApiController
    {
        [HttpGet]
        [Route("Countries")]
        public IHttpActionResult Countries()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.COUNTRies.ToList());
                }
            }
            catch(Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpGet]
        [Route("State/{CID:int}")]
        public IHttpActionResult State(int CID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.STATEs.Where(m=>m.CID==CID).ToList());
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpGet]
        [Route("PGS")]
        public IHttpActionResult PGS()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.PGS1.ToList());
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpGet]
        [Route("Gets/{EID:int}")]
        public IHttpActionResult Gets(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.PGS1.Find(EID));
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpGet]
        [Route("Get/{EID:int}",Name ="PG1")]
        public IHttpActionResult Get(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.PGS1.Find(EID));
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpPost]
        [Route("Save")]
        public IHttpActionResult Save(PG1 vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(vm).State = EntityState.Added;
                    obj.SaveChanges();
                    return Created(Url.Link("PG1", new { EID = vm.EID }),"Data Saved.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpPut]
        [Route("Update")]
        public IHttpActionResult Update(PG1 vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(vm).State = EntityState.Modified;
                    obj.SaveChanges();
                    return Ok("Data Updated.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpDelete]
        [Route("Delete/{EID:int}")]
        public IHttpActionResult Delete(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(obj.PGS1.Find(EID)).State = EntityState.Deleted;
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

    }
}

First you install ngx-bootstrap for modal popup & datepicker using below command

npm install ngx-bootstrap@2.0.5 --save
or
npm install ngx-bootstrap@3.0.1 --save

After that you inject in app.module file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CreateempComponent } from './emp/createemp.component';
import { FormsModule } from '@angular/forms';
import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';
import { ModalModule } from 'ngx-bootstrap';
import { EmpServices } from './emp/emp.services';
import { HttpClientModule } from '@angular/common/http';


@NgModule({
  declarations: [
    AppComponent,
    CreateempComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    BsDatepickerModule.forRoot(),
    ModalModule.forRoot(),
    HttpClientModule
  ],
  providers: [EmpServices],
  bootstrap: [AppComponent]
})
export class AppModule { }






Angular Model :

export class COUNTRY {
    CID: number;
    CNAME: string;
}
export class STATE {
    SID: number;
    SNAME: string;
    CID: number;
}
export class IPGS {
    EID: number;
    NAME: string;
    DOJ: Date;
    CID: number;
    SID: number;
}

Angular Service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { IPGS, COUNTRY, STATE } from './emp.model';
import 'rxjs/add/operator/toPromise';



@Injectable()
export class EmpServices {
    baseUrl = 'http://localhost:2813/api/Pgs';
    constructor(private http: HttpClient) {
    }
    Getc(): Promise<COUNTRY[]> {
        return this.http.get<COUNTRY[]>(`${this.baseUrl}/${'Countries'}`)
        .toPromise();
    }
    Gets(cid: number): Promise<STATE[]> {
        return this.http.get<STATE[]>(`${this.baseUrl}/${'State'}/${cid}`)
        .toPromise();
    }
    Get(eid: number): Promise<IPGS> {
        return this.http.get<IPGS>(`${this.baseUrl}/${'Gets'}/${eid}`)
        .toPromise();
    }
    Getp(): Promise<IPGS[]> {
        return this.http.get<IPGS[]>(`${this.baseUrl}/${'PGS'}`)
        .toPromise();
    }
    Save(vm: IPGS): Promise<string>  {
        return this.http.post<string>(`${this.baseUrl}/${'Save'}`
        , JSON.stringify(vm)
        , { headers : new HttpHeaders({'Content-Type': 'application/json' })}
        ).toPromise();
    }
    Update(vm: IPGS): Promise<string>  {
        return this.http.put<string>(`${this.baseUrl}/${'Update'}`
        , JSON.stringify(vm)
        , { headers : new HttpHeaders({'Content-Type': 'application/json' })}
        ).toPromise();
    }
    Delete(eid: number): Promise<string>  {
        return this.http.delete<string>(`${this.baseUrl}/${'Delete'}/${eid}`
        , { headers : new HttpHeaders({'Content-Type': 'application/json' })}
        ).toPromise();
    }
}

Angular Component :

import { Component, OnInit, TemplateRef } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
import {IPGS, COUNTRY, STATE} from './emp.model';
import { EmpServices } from './emp.services';
import { NgForm } from '@angular/forms';


@Component({
  selector: 'app-createemp',
  templateUrl: './createemp.component.html',
  styleUrls: ['./createemp.component.css']
})
export class CreateempComponent implements OnInit {
  modalRef: BsModalRef;
  PGS: IPGS;
  listc: COUNTRY[];
  lists: STATE[];
  list: IPGS[];
  eid: number;
  header: string;
  constructor(private modalService: BsModalService, private es: EmpServices) { }

  ngOnInit() {
    this.CLR();
    this.es.Getc().then(data => this.listc = data);
    this.fill();
  }
  openModal(template: TemplateRef<any>) {
    this.header = 'Add New';
    this.CLR();
    this.modalRef = this.modalService.show(template);
  }
  fillddl(): void {
    this.fx(this.PGS.CID);
}
fx(cid: number): void {
this.es.Gets(cid).then(data => {
  this.lists = data;
});
}
save(isValid: boolean): void {
if (isValid === false) {
  if (this.eid === undefined) {
    this.es.Save(this.PGS).then(data => {
      alert(data);
      this.fill();
      this.modalService.hide(1);
    });
  } else {
    this.es.Update(this.PGS).then(data => {
      alert(data);
      this.fill();
    });
  }
  this.modalService.hide(1);
}
}
edit(id: number, template: TemplateRef<any>): void {
  this.header = 'Edit';
  this.eid = id;
  this.es.Get(id).then(data =>  {
      this.PGS = data;
      const dt = new Date(this.PGS.DOJ);
      const dt1 = (dt.getMonth() + 1) + '/' + dt.getDate() + '/' + dt.getFullYear();
      this.PGS.DOJ = new Date(dt1);
      this.fx(this.PGS.CID);
    });
  this.modalRef = this.modalService.show(template);
}
del(id: number, template1: TemplateRef<any>): void {
  this.eid = id;
  this.modalRef = this.modalService.show(template1);
}
yes(): void {
  this.es.Delete(this.eid).then(data => {
    alert(data);
    this.fill();
    this.modalService.hide(1);
  });
}
fill(): void {
  this.es.Getp().then(data => this.list = data);
}
reset(): void {
  this.CLR();
}
  CLR(): void {
    this.PGS = {
      EID: null,
      NAME: null,
      DOJ: null,
      CID: null,
      SID: null
    };
    this.eid = undefined;
  }
}


Angular Html :

       <div class="row">
    <button type="button" class="btn btn-primary" (click)="openModal(template)">Add New</button>
</div><br>
<div class="row">
    <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
        <thead class="bg bg-primary">
            <tr>
                <th>SL NO.</th>
                <th>NAME</th>
                <th>DOJ</th>
                <th>ACTION</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let c of list;let i=index">
                <td>{{i+1}}</td>
                <td>{{c.NAME}}</td>
                <td>{{c.DOJ|date:'dd-MMM-yyyy'}}</td>
                <td>
                        <button type="button" style="width:70px" class="btn btn-primary" (click)="edit(c.EID,template)">Edit</button> |
                     <button type="button" (click)="del(c.EID,template1)" style="width:70px" class="btn btn-primary" >Delete</button>
                
                </td>
            </tr>
        </tbody>
    </table>
</div>
 
<ng-template #template>
  <div class="modal-header">
    <h4 class="modal-title pull-left">{{header}}</h4>
    <button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <form class="form-horizontal" #frmEmp="ngForm">
      <div class="form-group" [class.has-error]="EID.invalid && EID.touched" [class.has-success]="EID.valid">
          <label class="control-label col-lg-2">EID</label>
          <div class="col-lg-6">
              <input type="text" class="form-control" name="EID" #EID="ngModel" [(ngModel)]="PGS.EID" required />
          </div>
          <span class="help-block" *ngIf="EID.invalid && EID.touched">Eid should not be blank.</span>
      </div>
      <div class="form-group" [class.has-error]="NAME.invalid && NAME.touched" [class.has-success]="NAME.valid">
          <label class="control-label col-lg-2">NAME</label>
          <div class="col-lg-6">
              <input type="text" class="form-control" name="NAME" #NAME="ngModel" [(ngModel)]="PGS.NAME" required />
          </div>
          <span class="help-block" *ngIf="NAME.invalid && NAME.touched">Name should not be blank.</span>
      </div>
      <div class="form-group" [class.has-error]="DOB.invalid && DOB.touched" [class.has-success]="DOB.valid">
          <label class="control-label col-lg-2">DOB</label>
          <div class="col-lg-6">
              <input type="text"  bsDatepicker class="form-control"  name="DOB" #DOB="ngModel" [(ngModel)]="PGS.DOJ" required />
          </div>
          <span class="help-block" *ngIf="DOB.invalid && DOB.touched">Name should not be blank.</span>
      </div>
      <div class="form-group" [class.has-error]="CID.invalid && CID.touched" [class.has-success]="CID.valid">
        <label class="control-label col-lg-2">COUNTRY</label>
        <div class="col-lg-6">
            <select (change)="fillddl()"  class="form-control" name="CID" #CID="ngModel" [(ngModel)]="PGS.CID" required >
                <option [ngValue]="null">Select</option>
                <option *ngFor="let c of listc" [value]="c.CID">{{c.CNAME}}</option>
            </select>
        </div>
        <span class="help-block" *ngIf="CID.invalid && CID.touched">Please select a country.</span>
    </div>
    <div class="form-group" [class.has-error]="SID.invalid && SID.touched" [class.has-success]="SID.valid">
        <label class="control-label col-lg-2">STATE</label>
        <div class="col-lg-6">
            <select class="form-control" name="SID" #SID="ngModel" [(ngModel)]="PGS.SID" required>
                <option [ngValue]="null">Select</option>
                <option *ngFor="let c of lists" [value]="c.SID">{{c.SNAME}}</option>
            </select>
        </div>
        <span class="help-block" *ngIf="SID.invalid && SID.touched">Please select a state.</span>
    </div>
    </form>
    
  </div>
  <div class="modal-footer">
      <input type="button" class="btn btn-primary" value="Submit" style="width:80px" (click)="save(frmEmp.invalid)" />
      <input type="button" class="btn btn-primary" value="Reset" style="width:80px" (click)="reset()" />
      <input type="button" class="btn btn-primary" value="Close" style="width:80px" (click)="modalRef.hide()" />
    
  </div>
</ng-template>

<ng-template #template1>
    <div class="modal-header">
      <h4 class="modal-title pull-left">Alert Message</h4>
      <button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <h2>Do you want to delete it ?</h2>
    </div>
    <div class="modal-footer">
        <input type="button" class="btn btn-primary" value="Yes" style="width:80px" (click)="yes()" />
        <input type="button" class="btn btn-primary" value="No" style="width:80px" (click)="modalRef.hide()" />
    </div>
</ng-template>