Tuesday 25 December 2018

Dynamic page in angularjs6 & webapi2


Web api code :

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

namespace WebApplication5.Controllers
{
    [RoutePrefix("api/Deptservice")]
    public class DeptserviceController : ApiController
    {
        [HttpGet]
        [Route("AllDepts")]
        public IHttpActionResult AllDepts()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.DEPTs.ToList());
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpGet]
        [Route("Dept/{DID:int}",Name ="Dept")]
        public IHttpActionResult Dept(int DID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    DEPTVM vm = obj.DEPTs.Select(p => new DEPTVM { DID = p.DID, DNAME = p.DNAME }).SingleOrDefault(e => e.DID == DID);
                    vm.ELIST = obj.EMPs.Where(m => m.DID == DID).ToList();
                    return Ok(vm);
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpPost]
        [Route("Save")]
        public IHttpActionResult Save(DEPTVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    DEPT dept = new Models.DEPT();
                    dept.DID = vm.DID;
                    dept.DNAME = vm.DNAME;
                    obj.DEPTs.Add(dept);
                    obj.SaveChanges();
                    obj.EMPs.AddRange(vm.ELIST.Select(p => new EMP { EID = p.EID, NAME = p.NAME, DID = vm.DID }));
                    obj.SaveChanges();
                    return Created(new Uri(Url.Link("Dept",new { DID=vm.DID })), "Data Saved.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpPut]
        [Route("Update/{DID:int}")]
        public IHttpActionResult Update([FromUri]int DID, [FromBody]DEPTVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    DEPT dept = obj.DEPTs.Find(DID);
                    dept.DNAME = vm.DNAME;
                    obj.SaveChanges();
                    obj.EMPs.RemoveRange(obj.EMPs.Where(p => p.DID == DID));
                    obj.SaveChanges();
                    obj.EMPs.AddRange(vm.ELIST.Select(p => new EMP { EID = p.EID, NAME = p.NAME, DID = vm.DID }));
                    obj.SaveChanges();
                    return Ok("Data Updated.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpDelete]
        [Route("Delete/{DID:int}")]
        public IHttpActionResult Delete([FromUri]int DID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    DEPT dept = obj.DEPTs.Find(DID);
                    obj.DEPTs.Remove(dept);
                    obj.SaveChanges();
                    obj.EMPs.RemoveRange(obj.EMPs.Where(p => p.DID == DID));
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

    }
}

angular model code:

export interface Iemp {
    EID: number;
    NAME: string;
    DID: number;
}
export interface Idept {
    DID: number;
    DNAME: string;
    ELIST: Iemp[];
}

angular service code :

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

@Injectable()
export class DynamicseriviceService {
baseUrl = 'http://localhost:2813/api/Deptservice';
  constructor(private http: HttpClient) { }
Gets(): Promise<Idept[]> {
  return this.http.get<Idept[]>(`${this.baseUrl}/${'AllDepts'}`)
  .toPromise();
}
Get(did: number): Promise<Idept> {
  return this.http.get<Idept>(`${this.baseUrl}/${'Dept'}/${did}`)
  .toPromise();
}
Save(vm: Idept): Promise<string> {
  return this.http.post<string>(`${this.baseUrl}/${'Save'}`
, JSON.stringify(vm)
 , { headers: new HttpHeaders({'Content-Type' : 'application/json' })}
 )
.toPromise();
}
Update(vm: Idept): Promise<string> {
  return this.http.put<string>(`${this.baseUrl}/${'Update'}/${vm.DID}`
, JSON.stringify(vm)
 , { headers: new HttpHeaders({'Content-Type' : 'application/json' })}
 )
.toPromise();
}
Delete(did: number): Promise<string> {
  return this.http.delete<string>(`${this.baseUrl}/${'Delete'}/${did}`
 , { headers: new HttpHeaders({'Content-Type' : 'application/json' })}
 )
.toPromise();
}
}

angular component code :

import { Component, OnInit, ViewChild } from '@angular/core';
import { Idept, Iemp } from './dynamic.model';
import { DynamicseriviceService } from './dynamicserivice.service';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-createdynamic',
  templateUrl: './createdynamic.component.html',
  styleUrls: ['./createdynamic.component.css']
})
export class CreatedynamicComponent implements OnInit {
 DEPT: Idept;
 list: Iemp[];
 listd: Idept[];
 @ViewChild('ctcForm') public frmDept: NgForm;
  constructor(private ds: DynamicseriviceService) { }

  ngOnInit() {
    this.CLR();
    this.fill();
  }
  CLR(): void {
    this.DEPT = {
      DID: null,
      DNAME: null,
      ELIST: new Array()
    };
    this.frmDept.reset();
    this.add();
  }
add(): void {
  this.DEPT.ELIST.push({EID: null, NAME: null, DID: null});
}
save(): void {
  this.ds.Save(this.DEPT).then(data => {
    alert(data);
    this.CLR();
    this.fill();
  });
}
update(): void {
  this.ds.Update(this.DEPT).then(data => {
    alert(data);
    this.CLR();
    this.fill();
  });
}
del(did: number): void {
  if (confirm('Do you want to delte it')) {
    this.ds.Delete(did).then(data => {
      alert(data);
      this.fill();
          });
  }
}

edit(did: number): void {
  this.ds.Get(did).then(data => this.DEPT = data);
}
fill(): void {
this.ds.Gets().then(data => { this.listd = data; });
}
reset(): void {
  this.CLR();
}
sub(d: Iemp): void {
  if (this.DEPT.ELIST.length > 1 ) {
    this.DEPT.ELIST.splice(this.DEPT.ELIST.indexOf(d), 1);
  }
}
}

angular view code :

<form class="form-horizontal" #ctcForm="ngForm">
    <div class="form-group" [class.has-error]="DID.invalid && DID.touched" [class.has-success]="DID.valid">
        <label class="control-label col-lg-4">DID</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" [(ngModel)]="DEPT.DID" #DID="ngModel" name="DID" required />
        </div>
        <span class="help-block" *ngIf="DID.invalid && DID.touched">
            DID should not be blank.
        </span>
    </div>
    <div class="form-group" [class.has-error]="DNAME.invalid && DNAME.touched" [class.has-success]="DNAME.valid">
        <label class="control-label col-lg-4">DNAME</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" [(ngModel)]="DEPT.DNAME" #DNAME="ngModel" name="DNAME" required />
        </div>
        <span class="help-block" *ngIf="DNAME.invalid && DNAME.touched">
            Dname should not be blank.
        </span>
    </div>
  </form>
    <div class="form-group">
        <label class="control-label col-lg-4"></label>
        <div class="col-lg-6">
            <table  class="table table-bordered table-bordered table-condensed table-hover table-responsive table-striped">
                <thead class="bg bg-danger">
                <tr style="text-align:center"><td>EID</td><td>NAME</td><td>ACTION</td></tr>
              </thead>
                <tr *ngFor="let c of DEPT.ELIST">
                  <td style="width:20px">
                    <input  type="text" class="form-control" [(ngModel)]="c.EID">
                  </td>
                  <td style="width:100px">
                    <input  type="text" class="form-control" [(ngModel)]="c.NAME">
                  </td>
                  <td style="width:10px">
                    <a style="color:green;" (click)="add()">Add</a> |
                    <a style="color:red;" (click)="sub(c)">Remove</a>
                  </td>
                </tr>
              </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="Save" style="width:80px" (click)="save()" class="btn btn-primary" />
            <input type="button" value="Update" style="width:80px" (click)="update()" class="btn btn-primary" />
            <input type="button" value="Reset" style="width:80px" (click)="reset()" class="btn btn-primary" />
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-lg-4"></label>
        <div class="col-lg-6">
            <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
                <thead class="bg bg-primary">
                    <tr>
                        <th>Sl No.</th>
                        <th>DNAME</th>
                        <th>ACTION</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let c of listd;let i=index">
                        <td>{{i+1}}</td>
                        <td>{{c.DNAME}}</td>
                        <td>
                            <a (click)="edit(c.DID)">Edit</a> |
                            <a (click)="del(c.DID)">Delete</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
  </form>



No comments:

Post a Comment