Wednesday 9 January 2019

CURD operation using angularjs6 , datatable & webapi2 with multiple delete.


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/Testservice")]
    public class TestserviceController : ApiController
    {
        [Route("Alltests")]
        [HttpGet]
        public IHttpActionResult Alltests()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.TESTs.ToList());
                }
            }
            catch(Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [Route("Gets")]
        [HttpGet]
        public IHttpActionResult Gets()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.TEST1.ToList());
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [Route("Get/{ID:int}",Name ="Test1")]
        [HttpGet]
        public IHttpActionResult Get(int ID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    TESTVM vm = obj.TEST1.Select(p => new TESTVM { ID = p.ID, NAME = p.NAME }).FirstOrDefault(x => x.ID == ID);
                    List<int> d = obj.TEST2.Where(m => m.EID == ID).Select(p => p.TID.Value).ToList();
                    List<TEST> lst1 = obj.TESTs.Where(p => d.Contains(p.TID)).ToList();
                    List<TEST> lst2 = obj.TESTs.Where(p => d.Contains(p.TID) == false).ToList();
                    List<TEST> lst3 = lst1.Select(p => new TEST { TID = p.TID, TNAME = p.TNAME, STATUS = true }).ToList();
                    vm.TLIST = lst2.Union(lst3).ToList();
                    return Ok(vm);
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [Route("Save")]
        [HttpPost]
        public IHttpActionResult Save(TESTVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    TEST1 ts = new TEST1();
                    ts.ID = vm.ID;
                    ts.NAME = vm.NAME;
                    obj.Entry(ts).State = EntityState.Added;
                    obj.SaveChanges();
                    obj.TEST2.AddRange(vm.TLIST.Where(p=>p.STATUS==true).Select(e => new TEST2 { EID=vm.ID, TID=e.TID }));
                    obj.SaveChanges();
                    return Created(new Uri(Url.Link("Test1", new { ID = vm.ID })), "Data Saved.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [Route("Update/{ID:int}")]
        [HttpPut]
        public IHttpActionResult Update([FromUri]int ID,[FromBody]TESTVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    TEST1 ts = obj.TEST1.Find(ID);
                    ts.NAME = vm.NAME;
                    obj.Entry(ts).State = EntityState.Modified;
                    obj.SaveChanges();
                    obj.TEST2.RemoveRange(obj.TEST2.Where(e => e.EID == ID));
                    obj.SaveChanges();
                    obj.TEST2.AddRange(vm.TLIST.Where(e=>e.STATUS==true).Select(e => new TEST2 { EID = vm.ID, TID = e.TID }));
                    obj.SaveChanges();
                    return Ok("Data Updated.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [Route("Delete/{ID:int}")]
        [HttpDelete]
        public IHttpActionResult Delete([FromUri]int ID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    TEST1 ts = obj.TEST1.Find(ID);
                    obj.Entry(ts).State = EntityState.Deleted;
                    obj.SaveChanges();
                    obj.TEST2.RemoveRange(obj.TEST2.Where(e => e.EID == ID));
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [Route("DeleteAll")]
        [HttpPatch]
        public IHttpActionResult DeleteAll([FromBody]List<int> lst)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {

                    obj.TEST1.RemoveRange(obj.TEST1.Where(e => lst.Contains(e.ID)));
                    obj.SaveChanges();
                    obj.TEST2.RemoveRange(obj.TEST2.Where(e => lst.Contains(e.EID.Value)));
                    obj.SaveChanges();
                    return Ok("All Data Deleted.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }

        }

    }
}

Angularjs Model :

export interface Itest {
TID: number;
TNAME: string;
STATUS: Boolean;
}

export interface Itest1 {
ID: number;
NAME: string;
TLIST: Itest[];
}

export interface Itest2 {
    ID: number;
    NAME: string;
}

Angularjs Service Code :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Itest, Itest1, Itest2 } from './ctc.model';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class CtcService {
    constructor(private http: HttpClient) { }
    baseUrl = 'http://localhost:2813/api/Testservice';
    Getc(): Promise<Itest[]> {
        return this.http.get<Itest[]>(`${this.baseUrl}/${'Alltests'}`)
            .toPromise();
    }
    Gets(): Promise<Itest2[]> {
        return this.http.get<Itest2[]>(`${this.baseUrl}/${'Gets'}`)
            .toPromise();
    }
    Get(id: number): Promise<Itest1> {
        return this.http.get<Itest1>(`${this.baseUrl}/${'Get'}/${id}`)
            .toPromise();
    }
    Save(vm: Itest1): Promise<string> {
        return this.http.post<string>(`${this.baseUrl}/${'Save'}`
            , JSON.stringify(vm)
            , { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
            .toPromise();
    }
    Update(vm: Itest1): Promise<string> {
        return this.http.put<string>(`${this.baseUrl}/${'Update'}/${vm.ID}`
            , JSON.stringify(vm)
            , { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
            .toPromise();
    }
    Delete(id: number): Promise<string> {
        return this.http.delete<string>(`${this.baseUrl}/${'Delete'}/${id}`
            , { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
            .toPromise();
    }
    Deleteall(id: any): Promise<string> {
        return this.http.patch<string>(`${this.baseUrl}/${'DeleteAll'}`
            , JSON.stringify(id)
            , { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
            .toPromise();
    }
}


Angularjs Component :

import { Component, OnInit, ViewChild } from '@angular/core';
import { Itest, Itest1 } from './ctc.model';
import { CtcService } from './ctc.service';
import { NgForm } from '@angular/forms';
import { Subject } from 'rxjs/Subject';

@Component({
  selector: 'app-createctc',
  templateUrl: './createctc.component.html',
  styleUrls: ['./createctc.component.css']
})
export class CreatectcComponent implements OnInit {
  TEST: Itest1;
  list = new Array();
  dtOptions: DataTables.Settings = {};
  dtTrigger: Subject<any> = new Subject();
  hcb: boolean;
  deleall = new Array();
  @ViewChild('frmTest') public frmTest: NgForm;
  constructor(private cs: CtcService) { }

  ngOnInit() {
    this.CLR();
    this.fill();
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 2
    };
  }
  fillh(): void {
    this.list.forEach(element => {
      element.SELECTED = this.hcb;
    });
  }
  fillc(): void {
    this.hcb = this.list.every(function (item: any) {
      return item.SELECTED === true;
    });
  }
  CLR(): void {
    this.TEST = {
      ID: null,
      NAME: null,
      TLIST: []
    };
    this.frmTest.reset();
    this.cs.Getc().then(data => this.TEST.TLIST = data);
  }
  edit(id: number): void {
    this.cs.Get(id).then(data => {
      this.TEST = data;
    });
  }
  del(id: number): void {
    if (confirm('Do you want to delete it ?')) {
      this.cs.Delete(id).then(data => {
        alert(data);
        window.location.reload();
      });
    }
  }

  reset(): void {
    this.CLR();
  }
  fill(): void {
    this.list = new Array();
    this.cs.Gets().then(data => {
      for (let index = 0; index < data.length; index++) {
        this.list.push({ ID: data[index].ID, NAME: data[index].NAME, SELECTED: false });
      }
      this.dtTrigger.next();
    });

  }
  save(): void {
    this.cs.Save(this.TEST).then(data => {
      alert(data);
      window.location.reload();
    });
  }
  delall(): void {
  this.deleall = new Array();
    this.list.forEach(element => {
      if (element.SELECTED === true) {
        this.deleall.push(element.ID);
      }
      });
      if (this.deleall.length > 0) {
        if (confirm('Do you want to delete it ?')) {
          this.cs.Deleteall(this.deleall).then(data => {
            alert(data);
            window.location.reload();
          });
        }
      } else {
        alert('Please select atleast one item from the list.');
      }
  }
  update(): void {
    this.cs.Update(this.TEST).then(data => {
      alert(data);
      this.CLR();
      this.fill();
    });
  }
}

Angularjs View :

<form class="form-horizontal" #frmTest="ngForm">
  <div class="form-group" [class.has-error]="ID.invalid && ID.touched" [class.has-success]="ID.valid">
      <label class="control-label col-lg-4">ID</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" [(ngModel)]="TEST.ID" #ID="ngModel" name="ID" required />
      </div>
      <span class="help-block" *ngIf="ID.invalid && ID.touched">
          ID 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-4">NAME</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" [(ngModel)]="TEST.NAME" #NAME="ngModel" name="NAME" required />
      </div>
      <span class="help-block" *ngIf="NAME.invalid && NAME.touched">
          Name should not be blank.
      </span>
  </div>
  <div class="form-group">
    <label class="control-label col-lg-4">HOBBY</label>
    <div class="col-lg-4">
        <div *ngFor="let c of TEST.TLIST;let i=index">
                <input type="checkbox"  [(ngModel)]="c.STATUS" #STATUS="ngModel" name="{{'STATUS'+i}}" [value]="c.TID" />{{c.TNAME}}
        </div>
    </div>
</div>
  <div class="form-group">
      <label class="control-label col-lg-4"></label>
      <div class="col-lg-4">
          <input type="button" class="btn btn-primary" value="Save" style="width:80px" (click)="save()" />
          <input type="button" class="btn btn-primary" value="Update" style="width:80px" (click)="update()" />
          <input type="button" class="btn btn-primary" value="Reset" style="width:80px" (click)="reset()" />
      </div>
  </div>
  <div class="form-group">
        <label class="control-label col-lg-4"></label>
        <div class="col-lg-8">
            <div style="border:1px solid #808080" >
                <table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover  table table-bordered table-condensed table-hover table-responsive table-striped">

                        <thead class="bg bg-primary">
                            <tr>
                                <th style="text-align:center"><input type="checkbox" name="hcb" [(ngModel)]="hcb" (change)="fillh()" /></th>
                                <th>Sl No.</th>
                                <th>NAME</th>
                                <th>ACTION</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr *ngFor="let d of list; let i = index">
                                <td style="text-align:center"><input type="checkbox"  name="{{'cb'+i}}" [(ngModel)]="d.SELECTED" (change)="fillc()" /></td>
                                <td>{{i+1}}</td>
                                <td>{{d.NAME}}</td>
                                <td>
                                    <a (click)="edit(d.ID)">Edit</a> | 
                                    <a (click)="del(d.ID)">Delete</a>
                                </td>
                            </tr>
                        </tbody>
                    </table>
        </div>
    </div>
    </div>

    <div class="form-group">
        <label class="control-label col-lg-4"></label>
        <div class="col-lg-4">
            <input type="button" class="btn btn-primary" value="Delete All" style="width:90px" (click)="delall()" />
        </div>
    </div>
</form>



No comments:

Post a Comment