Saturday, 29 December 2018

CURD operation using angularjs6 , datatable & webapi2




Webapi Code :

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/Bbsrservices")]
    public class BbsrservicesController : ApiController
    {
        [HttpGet]
        [Route("Bbsrs")]
        public HttpResponseMessage Bbsrs()
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.BBSRs.ToList());
                }
            }
            catch(Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpGet]
        [Route("Bbsr/{BID:int}" ,Name ="Bbsr")]
        public HttpResponseMessage Bbsrs(int BID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    BBSRVM vm = obj.BBSRs.Select(m => new BBSRVM { BID = m.BID, NAME = m.NAME }).FirstOrDefault(p => p.BID == BID);
                    vm.CLIST = obj.CTCs.Where(e => e.BID == BID).ToList();
                    return Request.CreateResponse(HttpStatusCode.OK, vm);
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpPost]
        [Route("Save")]
        public HttpResponseMessage Save(BBSRVM vm)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    BBSR bbsr = new BBSR();
                    bbsr.BID = vm.BID;
                    bbsr.NAME = vm.NAME;
                    obj.Entry(bbsr).State = EntityState.Added;
                    obj.SaveChanges();
                    obj.CTCs.AddRange(vm.CLIST.Select(p => new CTC { NAME = p.NAME, GENDER = p.GENDER, MSTATUS = p.MSTATUS, BID = vm.BID }));
                    obj.SaveChanges();
                    var req = Request.CreateResponse(HttpStatusCode.Created, "Data Saved.");
                    req.Headers.Location = new Uri(Url.Link("Bbsr", new { BID = vm.BID }));
                    return req;
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpPut]
        [Route("Update/{BID:int}")]
        public HttpResponseMessage Update([FromUri]int BID,[FromBody]BBSRVM vm)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    BBSR bbsr = obj.BBSRs.Find(BID);
                    bbsr.NAME = vm.NAME;
                    obj.Entry(bbsr).State = EntityState.Modified;
                    obj.SaveChanges();
                    obj.CTCs.RemoveRange(obj.CTCs.Where(e => e.BID == BID));
                    obj.SaveChanges();
                    obj.CTCs.AddRange(vm.CLIST.Select(p => new CTC { NAME = p.NAME, GENDER = p.GENDER, MSTATUS = p.MSTATUS, BID = p.BID }));
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Updated.");
                    
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpDelete]
        [Route("Delete/{BID:int}")]
        public HttpResponseMessage Delete([FromUri]int BID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    BBSR bbsr = obj.BBSRs.Find(BID);
                    obj.Entry(bbsr).State = EntityState.Deleted;
                    obj.SaveChanges();
                    obj.CTCs.RemoveRange(obj.CTCs.Where(e => e.BID == BID));
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Deleted.");

                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }

    }
}


Angular Model :

export interface Ibbsr {
    BID: number;
    NAME: string;
    CLIST: Ictc[];
}

export interface Ictc {
    CID: number;
    NAME: string;
    GENDER: string;
    MSTATUS: string;
    BID: number;
}


Angularjs Service :

import { Injectable } from '@angular/core' ;
import { HttpClient, HttpHeaders } from '@angular/common/http' ;
import { Ibbsr } from './bbsr.model';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class BbsrService {
    baseUrl = 'http://localhost:2813/api/Bbsrservices';
    constructor(private http: HttpClient) { }

    Save(bbsr: Ibbsr): Promise<string> {
        return this.http.post<string>(`${this.baseUrl}/${'Save'}`
    , JSON.stringify(bbsr)
     , {headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
     .toPromise();
    }
    Update(bbsr: Ibbsr): Promise<string> {
        return this.http.put<string>(`${this.baseUrl}/${'Update'}/${bbsr.BID}`
    , JSON.stringify(bbsr)
     , {headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
     .toPromise();
    }
    Delete(bid: number): Promise<string> {
        return this.http.delete<string>(`${this.baseUrl}/${'Delete'}/${bid}`
     , {headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
     .toPromise();
    }
    Get(bid: number): Promise<Ibbsr> {
        return this.http.get<Ibbsr>(`${this.baseUrl}/${'Bbsr'}/${bid}`)
     .toPromise();
    }
    Gets(): Promise<Ibbsr[]> {
        return this.http.get<Ibbsr[]>(`${this.baseUrl}/${'Bbsrs'}`)
     .toPromise();
    }
}

List Component :


import { Component, OnInit, OnDestroy } from '@angular/core';
import { BbsrService } from './bbsr.service';
import { Ibbsr, Ictc} from './bbsr.model';
import { Subject } from 'rxjs/Subject';

@Component({
  selector: 'app-listbbsr',
  templateUrl: './listbbsr.component.html',
  styleUrls: ['./listbbsr.component.css']
})
export class ListbbsrComponent implements OnDestroy, OnInit {
list: Ibbsr[];
dtOptions: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject();
  constructor(private bs: BbsrService) { }

  ngOnInit() {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 2
    };
    this.fill();
  }
  fill(): void {
    this.bs.Gets().then(data => {
      this.list = data;
      this.dtTrigger.next();
    });
  }
  del(id: number): void {

    if (confirm('Do you want to delete it ?') ) {
      this.bs.Delete(id).then(data => {
        this.fill();
      });
    }

  }
  ngOnDestroy(): void {
    this.dtTrigger.unsubscribe();
  }
}


List View :

<div class="form-group">
    <div class="col-lg-4">
        <input type="button" value="Add New" [routerLink]="['/create']" style="width:80px" class="btn btn-primary" />
     </div>

    <label class="control-label col-lg-4"></label>
</div><br><br>
<div style="border:1px solid #808080">
  <table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover table table-bordered table-bordered table-condensed table-hover table-responsive table-striped">
  <thead class="bg bg-primary">
    <tr>
      <th>Sl No.</th>
      <th>NAME</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>
      <input type="button" style="width:80px" value="Edit" class="btn btn-primary" [routerLink]='["/create",c.BID]' /> |
      <input type="button" style="width:80px" value="Delete" class="btn btn-primary" (click)="del(c.BID)"/>
    </td>
    </tr>
  </tbody>
</table>
</div>

Create Component :

import { Component, OnInit, ViewChild } from '@angular/core';
import { Ibbsr, Ictc } from './bbsr.model';
import { NgForm } from '@angular/forms';
import { BbsrService } from './bbsr.service';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-createbbsr',
  templateUrl: './createbbsr.component.html',
  styleUrls: ['./createbbsr.component.css']
})
export class CreatebbsrComponent implements OnInit {
@ViewChild('bbsrForm') public  bbsrFrm: NgForm;
bid: number;
BBSR: Ibbsr;
  constructor(private bs: BbsrService, private rc: Router, private ar: ActivatedRoute) { }
  ngOnInit() {
    this.bid = this.ar.snapshot.params['id'];
    this.CLR();
    if (this.bid !== 0) {
      this.bs.Get(this.bid).then(data => this.BBSR = data);
    }
  }
add(): void {
  this.BBSR.CLIST.push({NAME: null, GENDER: null, MSTATUS: null, BID: null, CID: null});
}
remove(d: Ictc): void {
this.BBSR.CLIST.splice(this.BBSR.CLIST.indexOf(d), 1);
}
save(): void {
if (this.bid === 0) {
  this.bs.Save(this.BBSR).then(data => {
    alert(data);
    this.CLR();
    this.rc.navigate(['/list']);
  });
} else {
  this.bs.Update(this.BBSR).then(data => {
    alert(data);
    this.CLR();
    this.rc.navigate(['/list']);
  });
}
this.bid = 0;
}
reset(): void {
  this.CLR();
}
  CLR(): void {
    this.BBSR = {
       BID: null,
       NAME: null,
      CLIST: new Array()
    };
    this.bbsrFrm.reset();
    this.add();
  }
}

Create View :

<form class="form-horizontal" #bbsrForm="ngForm">
  <div class="form-group" [class.has-success]="BID.valid" [class.has-error]="BID.invalid && BID.touched">
      <label class="control-label col-lg-4">BID</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" required [(ngModel)]="BBSR.BID" #BID="ngModel" name="BID" />
      </div>
      <span class="help-block" *ngIf="BID.invalid && BID.touched">
          Bid should not be blank.
      </span>
  </div>
  <div class="form-group" [class.has-success]="NAME.valid" [class.has-error]="NAME.invalid && NAME.touched">
      <label class="control-label col-lg-4">NAME</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" required [(ngModel)]="BBSR.NAME" #NAME="ngModel" name="NAME" />
      </div>
      <span class="help-block" *ngIf="NAME.invalid && NAME.touched">
          Name should not be blank.
      </span>
  </div>
</form>
<div class="form-group">
  <label class="control-label col-lg-4"></label>
  <div class="col-lg-8">
      <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
          <thead class="bg bg-danger">
              <tr >
                  <th>NAME</th>
                  <th>GENDER</th>
                  <th>MARITIAL STATUS</th>
                  <th style="text-align:center"><a (click)="add()">Add</a></th>
              </tr>
          </thead>
          <tbody>
              <tr *ngFor="let c of BBSR.CLIST;let i=index">
                  <td><input type="text" class="form-control" name="NAME" [(ngModel)]="c.NAME" /></td>
                  <td><input type="radio" name={{i}}  value="Male"  [(ngModel)]="c.GENDER" />Male&nbsp;
                    <input  type="radio" name={{i}} value="Female" [(ngModel)]="c.GENDER" />Female</td>
                  <td>
                      <select class="form-control" [(ngModel)]="c.MSTATUS" #MSTATUS="ngModel" name={{i}}>
                      <option [ngValue]="null">Select</option>
                      <option value='Married'>Married</option>
                      <option value='Unmarried'>Unmarried</option>
                      </select>
                  </td>
                  <td style="text-align:center">
                       <a (click)="remove(c)">Remove</a>
                  </td>
              </tr>
          </tbody>
      </table>
  </div>
</div>
<form class="form-horizontal">
  <div class="form-group">
    <label class="control-label col-lg-4"></label>
      <div class="col-lg-4">
         <input type="button" value="Submit" (click)="save()" style="width:80px" class="btn btn-primary" />
          <input type="button" value="Reset" (click)="reset()" style="width:80px" class="btn btn-primary" /><br><br>
          <a [routerLink]="['/list']">Back To List</a>
      </div>
   
  </div>
</form>



App View :

 <div style="padding:5px" class="container">
    
      <ul class="nav nav-tabs">
    
       <li routerLinkActive="Active">
    
         <a routerLink="list">Department</a>
    
       </li>
    
       <li routerLinkActive="Active">
    
          <a routerLink="list">Employee</a>
    
        </li>
    
      </ul>
    
    <br>
    
    <router-outlet></router-outlet>
    
    </div>
     



No comments:

Post a Comment