Wednesday, 21 November 2018

CURD operation & example of pipe in angularjs6 & webapi2




Web api 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/Authorservices")]
    public class AuthorservicesController : ApiController
    {
        [HttpGet]
        [Route("Countries")]
        public HttpResponseMessage Countries()
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.COUNTRies.ToList());
                }
            }
            catch(Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpGet]
        [Route("Hobbies")]
        public HttpResponseMessage Hobbies()
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.HOBBies.ToList());
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpGet]
        [Route("Authors")]
        public HttpResponseMessage Authors()
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.AUTHORs.ToList());
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpGet]
        [Route("Author/{AID:int}",Name ="Get1")]
        public HttpResponseMessage Author(int AID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    AUTHORVM vm = obj.AUTHORs.Where(e => e.AID == AID).Select(p => new AUTHORVM { AID = p.AID, NAME = p.NAME, ADDRESS = p.ADDRESS, PASSWORD = p.PASSWORD, GENDER = p.GENDER, EMAIL = p.EMAIL, SALARY = p.SALARY, DOB = p.DOB, CID = p.CID, SID = p.SID }).SingleOrDefault(m => m.AID == AID);
                    vm.HLIST = obj.HMAPs.Where(e => e.WID == AID).Select(p => p.HID.Value).ToList();
                    return Request.CreateResponse(HttpStatusCode.OK, vm);
                }
            }

            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpGet]
        [Route("States/{CID:int}")]
        public HttpResponseMessage States(int CID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                 
                    return Request.CreateResponse(HttpStatusCode.OK, obj.STATEs.Where(m=>m.CID==CID).ToList());
                }
            }

            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpPost]
        [Route("Save")]
        public HttpResponseMessage Save(AUTHORVM vm)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    AUTHOR auth = new AUTHOR();
                    auth.AID = vm.AID;
                    auth.NAME = vm.NAME;
                    auth.ADDRESS = vm.ADDRESS;
                    auth.PASSWORD = vm.PASSWORD;
                    auth.GENDER = vm.GENDER;
                    auth.EMAIL = vm.EMAIL;
                    auth.SALARY = vm.SALARY;
                    auth.DOB = vm.DOB;
                    auth.CID = vm.CID;
                    auth.SID = vm.SID;
                    obj.Entry(auth).State = EntityState.Added;
                    obj.SaveChanges();
                    obj.HMAPs.AddRange(vm.HLIST.Select(p => new HMAP { WID=vm.AID, HID=p }).ToList());
                    obj.SaveChanges();
                    var req= Request.CreateResponse(HttpStatusCode.Created, "Data Saved.");
                    req.Headers.Location = new Uri(Url.Link("Get1", new { AID = vm.AID }));
                    return req;
                }
            }

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

        [HttpPut]
        [Route("Update/{AID:int}")]
        public HttpResponseMessage Update([FromUri]int AID,[FromBody]AUTHORVM vm)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    AUTHOR auth = obj.AUTHORs.Find(AID);
                    auth.NAME = vm.NAME;
                    auth.ADDRESS = vm.ADDRESS;
                    auth.PASSWORD = vm.PASSWORD;
                    auth.GENDER = vm.GENDER;
                    auth.EMAIL = vm.EMAIL;
                    auth.SALARY = vm.SALARY;
                    auth.DOB = vm.DOB;
                    auth.CID = vm.CID;
                    auth.SID = vm.SID;
                    obj.Entry(auth).State = EntityState.Modified;
                    obj.SaveChanges();
                    obj.HMAPs.RemoveRange(obj.HMAPs.Where(e => e.WID == AID).ToList());
                    obj.SaveChanges();
                    obj.HMAPs.AddRange(vm.HLIST.Select(p => new HMAP { WID = vm.AID, HID = p }).ToList());
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Updated.");
                   
                }
            }

            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpDelete]
        [Route("Delete/{AID:int}")]
        public HttpResponseMessage Delete([FromUri]int AID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    AUTHOR auth = obj.AUTHORs.Find(AID);
                   obj.Entry(auth).State = EntityState.Deleted;
                    obj.SaveChanges();
                    obj.HMAPs.RemoveRange(obj.HMAPs.Where(e => e.WID == AID).ToList());
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Deleted.");

                }
            }

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

    }
}


Angularjs Code: 

<form class="form-horizontal" #frmauthor="ngForm">
           
  <div class="form-group " [class.has-error]="AID.invalid && AID.touched" [class.has-success]="AID.valid" >
      <label class="control-label col-lg-4">AID</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" name="AID" required [(ngModel)]="AUTHOR.AID" #AID="ngModel" />
      </div>
      <span class="help-block has-error" *ngIf="AID.invalid && AID.touched">
          AID 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" name="NAME" required [(ngModel)]="AUTHOR.NAME" #NAME="ngModel" />
      </div>
      <span class="help-block has-error" *ngIf="NAME.invalid && NAME.touched">
          Name should not be blank.
      </span>
  </div>
  <div class="form-group " [class.has-error]="ADDRESS.invalid && ADDRESS.touched" [class.has-success]="ADDRESS.valid">
    <label class="control-label col-lg-4">ADDRESS</label>
    <div class="col-lg-4">
        <textarea class="form-control" name="ADDRESS" required [(ngModel)]="AUTHOR.ADDRESS" #ADDRESS="ngModel"></textarea>
    </div>
    <span class="help-block has-error" *ngIf="ADDRESS.invalid && ADDRESS.touched">
        Address should not be blank.
    </span>
</div>
  <div class="form-group " [class.has-error]="PASSWORD.invalid && PASSWORD.touched" [class.has-success]="PASSWORD.valid">
      <label class="control-label col-lg-4">PASSWORD</label>
      <div class="col-lg-4">
          <input type="password" minlength="6" maxlength="8" class="form-control" name="PASSWORD" required [(ngModel)]="AUTHOR.PASSWORD" #PASSWORD="ngModel" />
      </div>
      <span class="help-block has-error" *ngIf="PASSWORD.errors?.required && PASSWORD.touched">
          Password should not be blank.
      </span>
      <span class="help-block has-error" *ngIf="PASSWORD.errors?.minlength">
          Password min length is 6.
      </span>
      <span class="help-block has-error" *ngIf="PASSWORD.errors?.maxlength">
          Password max length is 8.
      </span>

  </div>
  <div class="form-group " [class.has-error]="GENDER.invalid && GENDER.touched" [class.has-success]="GENDER.valid">
      <label class="control-label col-lg-4">GENDER</label>
      <div class="col-lg-4">
          <input type="radio" value="Male" name="GENDER" required [(ngModel)]="AUTHOR.GENDER" #GENDER="ngModel" />Male
          <input type="radio" value="Female" name="GENDER" required [(ngModel)]="AUTHOR.GENDER" #GENDER="ngModel" />Female
      </div>
      <span class="help-block has-error" *ngIf="GENDER.invalid && GENDER.touched">
          Please select a gender.
      </span>
  </div>
  <div class="form-group " [class.has-error]="EMAIL.invalid && EMAIL.touched" [class.has-success]="EMAIL.valid">
      <label class="control-label col-lg-4">EMAIL</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" pattern="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" name="EMAIL" required [(ngModel)]="AUTHOR.EMAIL" #EMAIL="ngModel" />
      </div>
      <span class="help-block has-error" *ngIf="EMAIL.invalid && EMAIL.touched && EMAIL.errors?.required">
          Email should not be blank.
      </span>
      <span class="help-block has-error" *ngIf="EMAIL.touched && EMAIL.errors?.pattern">
          Invalid email id.
      </span>
  </div>
  <div class="form-group " [class.has-error]="SALARY.invalid && SALARY.touched" [class.has-success]="SALARY.valid">
      <label class="control-label col-lg-4">SALARY</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" name="SALARY" required [(ngModel)]="AUTHOR.SALARY" #SALARY="ngModel" />
      </div>
      <span class="help-block has-error" *ngIf="SALARY.invalid && SALARY.touched">
          Salary 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-4">DOB</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" name="DOB" required [(ngModel)]="AUTHOR.DOB" #DOB="ngModel" />
      </div>
      <span class="help-block has-error" *ngIf="DOB.invalid && DOB.touched">
          Dob 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-4">COUNTRY</label>
      <div class="col-lg-4">
          <select class="form-control" name="CID" (change)="fillddl()" required [(ngModel)]="AUTHOR.CID" #CID="ngModel">
              <option [ngValue]="null">Select</option>
              <option *ngFor="let c of listc" [value]="c.CID" >{{c.CNAME}}</option>
          </select>
      </div>
      <span class="help-block has-error" *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-4">STATE</label>
      <div class="col-lg-4">
          <select class="form-control" name="SID" required [(ngModel)]="AUTHOR.SID" #SID="ngModel">
              <option [ngValue]="null">Select</option>
              <option *ngFor="let c of lists" [value]="c.SID">{{c.SNAME}}</option>
          </select>
      </div>
      <span class="help-block has-error" *ngIf="SID.invalid && SID.touched">
          Please select a country.
      </span>
  </div>
  <div class="form-group " [class.has-error]="HLIST.invalid && HLIST.touched" [class.has-success]="HLIST.valid">
      <label class="control-label col-lg-4">HOBBY</label>
      <div class="col-lg-4">
          <select class="form-control" multiple name="HLIST" required [(ngModel)]="AUTHOR.HLIST" #HLIST="ngModel">
          
              <option *ngFor="let c of listh" [value]="c.HID">{{c.HNAME}}</option>
          </select>
      </div>
      <span class="help-block has-error" *ngIf="HLIST.invalid && HLIST.touched">
          Please select a hobby.
      </span>
  </div>
  <div class="form-group">
      <label class="control-label col-lg-4"></label>
      <div class="col-lg-4">
        <input type="button" value="Save" class="btn btn-primary" style="width:80px" (click)="save(frmauthor.valid)" />
          <input type="button" value="Update" class="btn btn-primary" style="width:80px" (click)="update(frmauthor.valid)" />
          <input type="button" value="Reset" class="btn btn-primary" style="width:80px" (click)="reset(frmauthor)" />
      </div>
  </div>
  <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-primary">
               <tr>
                   <th>Sl No.</th>
                   <th>NAME</th>
                   <th>ADDRESS</th>
                   <th>GENDER</th>
                   <th>SALARY</th>
                   <th>DOB</th>
                   <th>ACTION</th>
               </tr>
           </thead>
           <tbody>
               <tr *ngFor="let c of list;let i=index">
                   <td>{{i+1|percent}}</td>
                   <td>{{c.NAME|CustomPipe:c.GENDER}}</td>
                   <td>{{c.ADDRESS|lowercase}}</td>
                   <td>{{c.GENDER|uppercase}}</td>
                   <td>{{c.SALARY|number:'.3'}}</td>
                   <td>{{c.DOB|date:'dd-MMM-yyyy'}}</td>
                   <td>
                       <a (click)="edit(c.AID)">Edit</a> | <a (click)="del(c.AID)">Delete</a>
                   </td>
               </tr>
           </tbody>
       </table>
    </div>
</div>
</form>

Angular Model: 

export interface Iauthor {
    AID: number;
    NAME: string;
    ADDRESS: string;
    PASSWORD: string;
    GENDER: string;
    EMAIL: string;
    SALARY: number;
    DOB: Date;
    CID: number;
    SID: number;
    HLIST: number[];
}
export interface Icountry {
    CID: number;
    CNAME: string;
}

export interface Istate {
    SID: number;
    SNAME: string;
    CID: number;
}

export interface Ihobby {
    HID: number;
    HNAME: string;
}

Angularjs Services :

import { Injectable } from '@angular/core';
import { NgForm } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Iauthor, Icountry, Istate, Ihobby } from '../author/author.model';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class AuthorServices {
    baseUrl = 'http://localhost:2813/api/Authorservices';
    constructor(private _http: HttpClient) {
    }
    Getc(): Promise<Icountry[]> {
        return this._http.get<Icountry[]>(`${this.baseUrl}/${'Countries'}`)
            .toPromise();
    }
    Geth(): Promise<Ihobby[]> {
        return this._http.get<Ihobby[]>(`${this.baseUrl}/${'Hobbies'}`)
            .toPromise();
    }
    Geta(): Promise<Iauthor[]> {
        return this._http.get<Iauthor[]>(`${this.baseUrl}/${'Authors'}`)
            .toPromise();
    }
    Get(AID: number): Promise<Iauthor> {
        return this._http.get<Iauthor>(`${this.baseUrl}/${'Author'}/${AID}`)
            .toPromise();
    }
    Gets(CID: number): Promise<Istate[]> {
        return this._http.get<Istate[]>(`${this.baseUrl}/${'States'}/${CID}`)
            .toPromise();
    }
    Save(author: Iauthor): Promise<string> {
        return this._http.post<string>(`${this.baseUrl}/${'Save'}`
            , JSON.stringify(author)
            , {
                headers: new HttpHeaders({ 'Content-Type': 'application/json' })
            })
            .toPromise();
    }
    Update(author: Iauthor): Promise<string> {
        return this._http.put<string>(`${this.baseUrl}/${'Update'}/${author.AID}`
            , JSON.stringify(author)
            , {
                headers: new HttpHeaders({ 'Content-Type': 'application/json' })
            })
            .toPromise();
    }
    Delete(aid: number): Promise<string> {
        return this._http.delete<string>(`${this.baseUrl}/${'Delete'}/${aid}`
            , {
                headers: new HttpHeaders({ 'Content-Type': 'application/json' })
            })
            .toPromise();
    }
}

Angular js Custom Pipe code :

import {Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'CustomPipe'})
export class BookPipe implements PipeTransform {
    transform(value: string, gender: string): string {
        if (gender.toLowerCase() === 'male') {
            return 'Mr. ' + value;
        } else {
            return 'Miss. ' +  value;
        }
    }
}


Angular js Componet Code: 

import { Component, OnInit, ViewChild } from '@angular/core';
import { Iauthor, Icountry, Istate, Ihobby } from '../author/author.model';
import { AuthorServices } from '../author/author.services';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {
  @ViewChild('frmauthor') private frmAuthor: NgForm;
  AUTHOR: Iauthor;
  listc: Icountry[];
  lists: Istate[];
  listh: Ihobby[];
  list: Iauthor[];
  constructor(private ahs: AuthorServices) { }

  ngOnInit() {
    this.CLR();
    this.ahs.Getc().then(data => this.listc = data);
    this.ahs.Geth().then(data => this.listh = data);
    this.fill();
  }
  del(aid: number): void {
    if (confirm('Do you want to delete it ?')) {
      this.ahs.Delete(aid).then(data => {
      alert(data);
      this.fill();
      });
    }
  }
  edit(aid: number): void {
    this.ahs.Get(aid).then(data => {
      this.fx(data.CID);
      this.AUTHOR = data;
    });
  }
  reset(fr: NgForm): void {
    fr.reset();
  }
  fill(): void {
    this.ahs.Geta().then(data => this.list = data);
  }
  fillddl(): void {
    this.fx(this.AUTHOR.CID);
  }
  fx(cid: number): void {
    this.ahs.Gets(cid).then(data => this.lists = data);
  }
  update(isValid): void {
    if (isValid) {
      this.ahs.Update(this.AUTHOR).then(data => {
        alert(data);
        this.CLR();
        this.fill();
      });
    }

  }
  save(isValid): void {
    if (isValid) {
      this.ahs.Save(this.AUTHOR).then(data => {
        alert(data);
        this.CLR();
        this.fill();
      });
    }

  }
  CLR(): void {
    this.frmAuthor.reset();
    this.AUTHOR = {
      AID: null,
      NAME: null,
      ADDRESS: null,
      PASSWORD: null,
      GENDER: null,
      EMAIL: null,
      SALARY: null,
      DOB: null,
      CID: null,
      SID: null,
      HLIST: []
    };
  }
}


Monday, 5 November 2018

CURD opration using angularjs6 & webapi2




Web api 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/Doorservices")]
    public class DoorservicesController : ApiController
    {
        [Route("Gets")]
        [HttpGet]
        public IHttpActionResult Gets()
        {
            try {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.EMPs.ToList());
                }
            }
            catch (Exception ex){
                return BadRequest(ex.Message);
            }
        }
        [Route("Get/{EID:int}",Name ="EMP")]
        [HttpGet]
        public IHttpActionResult Get(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.EMPs.SingleOrDefault(e=>e.EID==EID));
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [Route("Save")]
        [HttpPost]
        public IHttpActionResult Save(EMP emp)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(emp).State = EntityState.Added;
                    obj.SaveChanges();
                    return Created(new Uri(Url.Link("EMP",new { EID=emp.EID})), "Data Saved.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [Route("Update/{EID:int}")]
        [HttpPut]
        public IHttpActionResult Update([FromUri]int EID,[FromBody]EMP emp)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(emp).State = EntityState.Modified;
                    obj.SaveChanges();
                    return Ok("Data Updated");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [Route("Delete/{EID:int}")]
        [HttpDelete]
        public IHttpActionResult Delete([FromUri]int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(obj.EMPs.Find(EID)).State = EntityState.Deleted;
                    obj.SaveChanges();
                    return Ok("Data Deleted");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }


    }
}

angularjs code

Model code;
export class DoorModel {
    EID: number;
    NAME: string;
}

Service code :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { DoorModel } from '../door/doormodel';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';


@Injectable()
export class DoorServices {
    baseUrl = 'http://localhost:2813/api/Doorservices';
    constructor(private _http: HttpClient) {
    }
    Save(emp: DoorModel): Promise<string> {
        return this._http.post<string>(`${this.baseUrl}/${'Save'}`, JSON.stringify(emp),
            { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }).toPromise();
    }
    Gets(): Promise<DoorModel[]> {
        return this._http.get<DoorModel[]>(`${this.baseUrl}/${'Gets'}`).toPromise();
    }
    Get(eid: number): Promise<DoorModel> {
        return this._http.get<DoorModel>(`${this.baseUrl}/${'Get'}/${eid}`)
            .toPromise();
    }
    Update(emp: DoorModel): Promise<string> {
        return this._http.put<string>(`${this.baseUrl}/${'Update'}/${emp.EID}`
            , JSON.stringify(emp), { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
            .toPromise();
    }
    Delete(eid: number): Promise<string> {
        return this._http.delete<string>(`${this.baseUrl}/${'Delete'}/${eid}`)
        .toPromise();
    }
}

Component  code :

import { Component, OnInit } from '@angular/core';
import { DoorModel } from '../door/doormodel';
import { DoorServices } from '../door/door.services';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {
  EMP: DoorModel;
  list: DoorModel[];
  constructor(private ds: DoorServices) { }

  ngOnInit() {
    this.CLR();
    this.fill();
  }
  CLR(): void {
    this.EMP = {
      EID: null,
      NAME: null
    };
  }
  save(Isvalid: boolean): void {
    if (Isvalid) {
      this.ds.Save(this.EMP).then(data => {
        alert(data);
        this.CLR();
        this.fill();
      });
    }

  }
  update(Isvalid: boolean): void {
    if (Isvalid) {
      this.ds.Update(this.EMP).then(data => {
        alert(data);
        this.CLR();
        this.fill();
      });
    }

  }
  reset(ngfrm: NgForm): void {
    ngfrm.reset();
  }
  fill(): void {
    this.ds.Gets().then(data => this.list = data);
  }
  Edit(eid: number): void {
    this.ds.Get(eid).then(data => this.EMP = data);
  }
  del(eid: number): void {
    if (confirm('Do you want to delete it ?')) {
      this.ds.Delete(eid).then(data => {
        alert(data);
        this.fill();
      });
    }

  }
}


view code :

<form class="form-horizontal" #empform="ngForm">
    <div class="form-group " [class.has-error]="EID.invalid && EID.touched" [class.has-success]="EID.valid">
        <label class="control-label col-lg-4">EID</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" [(ngModel)]="EMP.EID" #EID="ngModel" required name="EID" />
        </div>
        <span class="help-block has-error" *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-4">NAME</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" [(ngModel)]="EMP.NAME" #NAME="ngModel" required name="NAME" />
        </div>
        <span class="help-block has-error" *ngIf="NAME.invalid && NAME.touched">
            Name should not be blank.
        </span>
    </div>
    <div class="form-group">
        <label class="control-label col-lg-4"></label>
        <div class="col-lg-4">
           <input type="button" value="Save" (click)="save(empform.valid)" style="width:80px" class="btn btn-primary" />
            <input type="button" value="Update" (click)="update(empform.valid)" style="width:80px" class="btn btn-primary" />
            <input type="button" value="Reset" (click)="reset(empform)" style="width:80px" class="btn btn-primary" />

        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-lg-4"></label>
        <div class="col-lg-4">
            <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
                <thead class="bg bg-primary">
                    <tr>
                        <th>Sl NO.</th>
                        <th>EID</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.EID}}</td>
                        <td>{{c.NAME}}</td>
                        <td>
                            <a (click)="Edit(c.EID)">Edit</a> |
                            <a (click)="del(c.EID)">Delete</a> 
            
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    
    </form>




Saturday, 7 July 2018

CRUD operation , all pipes using Angularjs5 and web api2


WEB API :

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

namespace WebApplication2.Controllers
{
    [RoutePrefix("api/Testservice")]
    public class TestserviceController : ApiController
    {
        [Route("Tests")]
        [HttpGet]
        public IHttpActionResult Tests()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.TESTs.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
           
        }

        [Route("Test/{TID:int}", Name ="Test")]
        [HttpGet]
        public IHttpActionResult Test(int TID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.TESTs.Find(TID));
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }

        [Route("Save")]
        [HttpPost]
        public IHttpActionResult Save(TEST tst)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(tst).State = EntityState.Added;
                    obj.SaveChanges();
                    return Created(new Uri(Url.Link("Test", new { TID = tst.TID })), "Data Saved.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }

        [Route("Update/{TID:int}")]
        [HttpPut]
        public IHttpActionResult Update([FromUri]int TID,[FromBody]TEST tst)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                 
                    obj.Entry(tst).State = EntityState.Modified;
                    obj.SaveChanges();
                    return Ok("Data Updated.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }

        [Route("Delete/{TID:int}")]
        [HttpDelete]
        public IHttpActionResult Delete([FromUri]int TID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {

                    obj.Entry(obj.TESTs.Find(TID)).State = EntityState.Deleted;
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }


    }
}

Angularjs View :

<form class="form-horizontal" #frmTest="ngForm">
    <div class="form-group " [class.has-error]="TID.invalid && TID.touched" [class.has-success]="TID.valid">
        <label class="control-label col-lg-4">TID</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="TID" [(ngModel)]="TEST.TID" #TID="ngModel" required />
            <span class="help-block" *ngIf="TID.invalid && TID.touched">
                TID should not blank.
            </span>
        </div>
    </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" name="NAME" [(ngModel)]="TEST.NAME" #NAME="ngModel" required />
            <span class="help-block" *ngIf="NAME.invalid && NAME.touched">
                Name should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="GENDER.invalid && GENDER.touched" [class.has-success]="GENDER.valid">
        <label class="control-label col-lg-4">GENDER</label>
        <div class="col-lg-4">
            <input type="radio"  name="GENDER" [(ngModel)]="TEST.GENDER" #GENDER="ngModel" required value="Male" />Male
            <input type="radio" name="GENDER" [(ngModel)]="TEST.GENDER" #GENDER="ngModel" required value="Female" />Female
            <span class="help-block" *ngIf="GENDER.invalid && GENDER.touched">
                Please select a gender.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="SALARY.invalid && SALARY.touched" [class.has-success]="SALARY.valid">
        <label class="control-label col-lg-4">SALARY</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="SALARY" [(ngModel)]="TEST.SALARY" #SALARY="ngModel" required />
            <span class="help-block" *ngIf="SALARY.invalid && SALARY.touched">
                Salary should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="DOB.invalid && DOB.touched" [class.has-success]="DOB.valid">
        <label class="control-label col-lg-4">DOB</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="DOB" [(ngModel)]="TEST.DOB" #DOB="ngModel" required />
            <span class="help-block" *ngIf="DOB.invalid && DOB.touched">
                DOB should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="MARK.invalid && MARK.touched" [class.has-success]="MARK.valid">
        <label class="control-label col-lg-4">MARK</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="MARK" [(ngModel)]="TEST.MARK" #MARK="ngModel" required />
            <span class="help-block" *ngIf="MARK.invalid && MARK.touched">
                Mark should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="PERCENTAGE.invalid && PERCENTAGE.touched" [class.has-success]="PERCENTAGE.valid">
        <label class="control-label col-lg-4">PERCENTAGE</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="PERCENTAGE" [(ngModel)]="TEST.PERCENTAGE" #PERCENTAGE="ngModel" required />
            <span class="help-block" *ngIf="PERCENTAGE.invalid && PERCENTAGE.touched">
                Percentage should not blank.
            </span>
        </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(frmTest.invalid)" >
            <input type="button" class="btn btn-primary" value="Update" style="width:80px" (click)="update(frmTest.invalid)">
            <input type="button" class="btn btn-primary" value="Reset" style="width:80px" (click)="reset()">
        </div>
    </div>
    <div class="row">
        <table style="width:1000px" class="table table-bordered table-condensed table-hover table-responsive table-striped">
            <thead class="bg bg-primary">
                <tr>
                    <th>Sl No.</th>
                    <th>TID</th>
                    <th>NAME</th>
                    <th>GENDER</th>
                    <th>SALARY</th>
                    <th >DOB</th>
                    <th>MARK</th>
                    <th>PERCENTAGE</th>
                    <th>ACTION</th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let c of list;let i=index">
                    <td>{{i+1}}</td>
                    <td>{{c.TID}}</td>
                    <td>{{c.NAME|uppercase|CusomPipe:c.GENDER}}</td>
                    <td>{{c.GENDER|lowercase}}</td>
                    <td>{{c.SALARY|currency:'UST':false}}</td>
                    <td>{{c.DOB|date:"dd-MMM-y"}}</td>
                    <td>{{c.MARK|number:'1.2-2'}}</td>
                    <td>{{c.PERCENTAGE|percent}}</td>
                    <td>
                        <a (click)="edit(c.TID)">Edit</a> |
                        <a (click)="del(c.TID)">Delete</a>
                    </td>
                </tr>
            </tbody>
        </table>

    </div>
    
</form>

Angularjs Model :

export class ITEST {
    TID: number;
    NAME: string;
    GENDER: string;
    SALARY: number;
    DOB: Date;
    MARK: number;
    PERCENTAGE: number;
}


Angularjs Services :

import { Injectable } from '@angular/core';
import { Http, Headers, Request, Response, RequestOptions, RequestMethod } from '@angular/http';
import { ITEST } from '../test/test.model';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class TestServices {
    constructor(private _http: Http) { }
    Get(tid: number): Promise<ITEST> {
        return this._http.get('http://localhost:3592/api/Testservice/Test/' + tid)
            .map((res: Response) => <ITEST>res.json())
            .toPromise();
    }
    Gets(): Observable<ITEST[]> {
        return this._http.get('http://localhost:3592/api/Testservice/Tests')
            .map((res: Response) => <ITEST[]>res.json());
    }
    Save(doc: ITEST): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Post, headers: headerOptions });
        return this._http.post('http://localhost:3592/api/Testservice/Save', JSON.stringify(doc), requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
    Update(doc: ITEST): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
        return this._http.put('http://localhost:3592/api/Testservice/Update/' + doc.TID, JSON.stringify(doc), requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
    Delete(tid: number): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Delete, headers: headerOptions });
        return this._http.delete('http://localhost:3592/api/Testservice/Delete/' + tid, requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
}

Angularjs Componet :

import { Component, OnInit } from '@angular/core';
import { ITEST } from '../test/test.model';
import { TestServices } from '../test/test.service';

@Component({
  selector: 'app-test-create',
  templateUrl: './test-create.component.html',
  styleUrls: ['./test-create.component.css']
})
export class TestCreateComponent implements OnInit {
  TEST: ITEST;
  list: ITEST[];
  constructor(private _ts: TestServices) { }

  ngOnInit() {
    this.reset();
    this.fill();
  }
  save(isValid: boolean): void {
    if (isValid === false) {
      this._ts.Save(this.TEST).then(data => {
        alert(data);
        this.reset();
        this.fill();
      });
    }
  }
  update(isValid: boolean): void {
    if (isValid === false) {
      this._ts.Update(this.TEST).then(data => {
        alert(data);
        this.reset();
        this.fill();
      });
    }
  }
  fill(): void {
    this._ts.Gets().subscribe(data => this.list = data);
  }
  edit(tid: number): void {
    this._ts.Get(tid).then(data => this.TEST = data);
  }
  del(tid: number): void {
    if (confirm('Do you want to delete it ?')) {
      this._ts.Delete(tid).then(data => {
        alert(data);
        this.fill();
      });
    }

  }
  reset(): void {
    this.TEST = {
      TID: null,
      NAME: null,
      GENDER: null,
      SALARY: null,
      DOB: null,
      MARK: null,
      PERCENTAGE: null
    };
  }
}


Angularjs Custom Pipe :

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'CusomPipe'
})
export class CusomPip implements PipeTransform {
    transform(value: string, gender: string): string {
        if (gender.toLowerCase() === 'male') {
            return 'Mr.' + value;
        } else {
            return 'Miss.' + value;
        }

    }

}



Sunday, 1 July 2018

CRUD operation & costume directive in angularjs5 & webapi2


View Model :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication2.Models
{
    public class DOCTORVM
    {
        public int DID { get; set; }
        public string NAME { get; set; }
        public string ADDRESS { get; set; }
        public string PASSWORD { get; set; }
        public string CPASSWORD { get; set; }
        public string GENDER { get; set; }
        public bool? ISMARRIED { get; set; }
        public int? CID { get; set; }
        public int? SID { get; set; }
        public List<int> HLIST { get; set; }
    }
}

Web API :

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

namespace WebApplication2.Controllers
{
    [RoutePrefix("api/Doctorservices")]
    public class DoctorservicesController : ApiController
    {
        [HttpGet]
        [Route("Countries")]
        public IHttpActionResult Countries()
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    return Ok(obj.COUNTRies.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpGet]
        [Route("Hobbies")]
        public IHttpActionResult Hobbies()
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    return Ok(obj.HOBBies.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpGet]
        [Route("Doctors")]
        public IHttpActionResult Doctors()
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    return Ok(obj.DOCTORs.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpGet]
        [Route("Doctor/{DID:int}",Name ="doctor")]
        public IHttpActionResult Doctor(int DID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    DOCTORVM vm = obj.DOCTORs.Select(e => new DOCTORVM { DID = e.DID, NAME = e.NAME, ADDRESS = e.ADDRESS, PASSWORD = e.PASSWORD,CPASSWORD=e.PASSWORD , GENDER = e.GENDER, ISMARRIED = e.ISMARRIED, CID = e.CID, SID = e.SID, HLIST = obj.HMAPs.Where(m => m.STID == DID).Select(p => p.HID.Value).ToList() }).SingleOrDefault(n => n.DID == DID);
                    return Ok(vm);
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpGet]
        [Route("State/{CID:int}")]
        public IHttpActionResult State(int CID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    return Ok(obj.STATEs.Where(e=>e.CID==CID).ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpPost]
        [Route("Save")]
        public IHttpActionResult Save(DOCTORVM vm)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    DOCTOR doc = new DOCTOR();
                    doc.DID = vm.DID;
                    doc.NAME = vm.NAME;
                    doc.ADDRESS = vm.ADDRESS;
                    doc.PASSWORD = vm.CPASSWORD;
                    doc.GENDER = vm.GENDER;
                    doc.ISMARRIED = vm.ISMARRIED;
                    doc.ISMARRIED = vm.ISMARRIED;
                    doc.CID = vm.CID;
                    doc.SID = vm.SID;
                    obj.DOCTORs.Add(doc);
                    obj.SaveChanges();
                    obj.HMAPs.AddRange(vm.HLIST.Select(e => new HMAP { HID = e, STID = vm.DID }));
                    obj.SaveChanges();
                    return Created(new Uri(Url.Link("doctor", new { DID = vm.DID })),"Data Saved.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpPut]
        [Route("Update/{DID:int}")]
        public IHttpActionResult Update([FromUri]int DID,[FromBody]DOCTORVM vm)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    DOCTOR doc = obj.DOCTORs.Find(DID);
                    doc.NAME = vm.NAME;
                    doc.ADDRESS = vm.ADDRESS;
                    doc.GENDER = vm.GENDER;
                    doc.ISMARRIED = vm.ISMARRIED;
                    doc.ISMARRIED = vm.ISMARRIED;
                    doc.CID = vm.CID;
                    doc.SID = vm.SID;
                    obj.SaveChanges();
                    obj.HMAPs.RemoveRange(obj.HMAPs.Where(e => e.STID == DID));
                    obj.SaveChanges();
                    obj.HMAPs.AddRange(vm.HLIST.Select(e => new HMAP { HID = e, STID = vm.DID }));
                    obj.SaveChanges();
                    return Ok("Data Updated.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpDelete]
        [Route("Delete/{DID:int}")]
        public IHttpActionResult Delete([FromUri]int DID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    DOCTOR doc = obj.DOCTORs.Find(DID);
                    obj.DOCTORs.Remove(doc);
                    obj.SaveChanges();
                    obj.HMAPs.RemoveRange(obj.HMAPs.Where(e => e.STID == DID));
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }




    }
}


Angularjs View :

<form #frmDoct="ngForm" class="form-horizontal">
    <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" name="DID" [(ngModel)]="DOCTOR.DID" #DID="ngModel" class="form-control" required />
            <span class="help-block" *ngIf="DID.invalid && DID.touched">DID should be not blank.</span>
        </div>
    </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" name="NAME" [(ngModel)]="DOCTOR.NAME" #NAME="ngModel" class="form-control" required />
            <span class="help-block" *ngIf="NAME.invalid && NAME.touched">Name should be not blank.</span>
        </div>
    </div>
    <div class="form-group" [class.has-error]="ADDRESS.invalid && ADDRESS.touched" [class.has-success]="ADDRESS.valid">
        <label class="control-label col-lg-4">ADDRESS</label>
        <div class="col-lg-4">
            <textarea name="ADDRESS" [(ngModel)]="DOCTOR.ADDRESS" #ADDRESS="ngModel" class="form-control" required ></textarea>
            <span class="help-block" *ngIf="ADDRESS.invalid && ADDRESS.touched">Address should be not blank.</span>
        </div>
    </div>
    <div class="form-group" [class.has-error]="PASSWORD.invalid && PASSWORD.touched" [class.has-success]="PASSWORD.valid">
        <label class="control-label col-lg-4">PASSWORD</label>
        <div class="col-lg-4">
            <input type="password" name="PASSWORD" minlength="6"  [(ngModel)]="DOCTOR.PASSWORD" #PASSWORD="ngModel" class="form-control" required />
            <span class="help-block">
                <span *ngIf="PASSWORD.errors?.required && PASSWORD.touched">Password should be not blank.</span>
                <span *ngIf="PASSWORD.errors?.minlength && PASSWORD.touched">Password min length is 6.</span>
            </span>
        </div>
    </div>
    <div class="form-group" [class.has-error]="CPASSWORD.invalid && CPASSWORD.touched" [class.has-success]="CPASSWORD.valid">
        <label class="control-label col-lg-4">CONFIRM PASSWORD</label>
        <div class="col-lg-4">
            <input type="password" name="CPASSWORD" minlength="6" appCompareValidator="PASSWORD"  [(ngModel)]="DOCTOR.CPASSWORD" #CPASSWORD="ngModel" class="form-control" required />
            <span class="help-block">
                <span *ngIf="CPASSWORD.errors?.required && CPASSWORD.touched">Confirm password should be not blank.</span>
                <span *ngIf="CPASSWORD.errors?.minlength && CPASSWORD.touched">Confirm password min length is 6.</span>
                <span *ngIf="CPASSWORD.errors?.notEqual  && CPASSWORD.touched && !CPASSWORD.errors?.minlength &&  !CPASSWORD.errors?.required">Password and confirm pasword must be same.</span>
            </span>
        </div>
    </div>
    <div class="form-group" [class.has-error]="GENDER.invalid && GENDER.touched" [class.has-success]="GENDER.valid">
        <label class="control-label col-lg-4">GENDER</label>
        <div class="col-lg-4">
            <input type="radio" name="GENDER" [(ngModel)]="DOCTOR.GENDER" #GENDER="ngModel" value="Male" required />Male
            <input type="radio" name="GENDER" [(ngModel)]="DOCTOR.GENDER" #GENDER="ngModel" value="Female" required />Female
            <span class="help-block" *ngIf="GENDER.invalid && GENDER.touched">Please select a gender.</span>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-lg-4">ARE YOU MARRIED ?</label>
        <div class="col-lg-4">
            <input type="checkbox" name="ISMARRIED" [(ngModel)]="DOCTOR.ISMARRIED" #ISMARRIED="ngModel"/>
        </div>
    </div>
    <div class="form-group" [class.has-error]="CID.invalid && CID.touched" [class.has-success]="CID.valid">
        <label class="control-label col-lg-4">COUNTRY</label>
        <div class="col-lg-4">
            <select name="CID" (change)="fillddl()" [(ngModel)]="DOCTOR.CID" #CID="ngModel" class="form-control" required >
                <option [ngValue]="null">Select</option>
                <option *ngFor="let c of listc" [value]="c.CID">{{c.CNAME}}</option>
            </select>
            <span class="help-block" *ngIf="CID.invalid && CID.touched">Please select a country.</span>
        </div>
    </div>
    <div class="form-group" [class.has-error]="SID.invalid && SID.touched" [class.has-success]="SID.valid">
        <label class="control-label col-lg-4">STATE</label>
        <div class="col-lg-4">
            <select name="SID" [(ngModel)]="DOCTOR.SID" #SID="ngModel" class="form-control" required>
                <option [ngValue]="null">Select</option>
                <option *ngFor="let c of lists" [value]="c.SID">{{c.SNAME}}</option>
            </select>
            <span class="help-block" *ngIf="SID.invalid && SID.touched">Please select a state.</span>
        </div>
    </div>
    <div class="form-group" [class.has-error]="HLIST.invalid && HLIST.touched" [class.has-success]="HLIST.valid">
        <label class="control-label col-lg-4">HOBBY</label>
        <div class="col-lg-4">
            <select name="HLIST" multiple [(ngModel)]="DOCTOR.HLIST" #HLIST="ngModel" class="form-control" required>
                <option *ngFor="let c of listh" [value]="c.HID">{{c.HNAME}}</option>
            </select>
            <span class="help-block" *ngIf="HLIST.invalid && HLIST.touched">Please select a hobby.</span>
        </div>
    </div>
    <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" class="btn btn-primary" (click)="save(frmDoct.invalid)" />
            <input type="button" value="Update" style="width:80px" class="btn btn-primary" (click)="update(frmDoct.invalid)" />
            <input type="button" value="Reset" style="width:80px" class="btn btn-primary" (click)="reset()" />
           
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-lg-4"></label>
        <div class="col-lg-4">
            <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
                <thead class="bg bg-primary">
                    <tr>
                        <th>DID</th>
                        <th>NAME</th>
                        <th>ACTION</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let c of list">
                        <td>{{c.DID}}</td>
                        <td>{{c.NAME}}</td>
                        <td>
                            <a (click)="edit(c.DID)">Edit</a> |
                            <a (click)="del(c.DID)">Delete</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</form>

Angularjs Costume Directive :

import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';
import { Directive, Input } from '@angular/core';

@Directive({
    selector: '[appCompareValidator]',
    providers: [{
        provide: NG_VALIDATORS,
        useExisting: CompareDirective,
        multi: true
    }]
})
export class CompareDirective implements Validator {
    @Input() appCompareValidator: string;
    validate(control: AbstractControl): { [key: string]: any } | null {
        const controlToCompare = control.parent.get(this.appCompareValidator);
        if (controlToCompare && controlToCompare.value !== control.value) {
            return { 'notEqual': true };
        }

        return null;
    }
}

Angularjs Model :

export interface Idoctor {
    DID: number;
    NAME: string;
    ADDRESS: string;
    PASSWORD: string;
    CPASSWORD: string;
    GENDER: string;
    ISMARRIED: boolean;
    CID: number;
    SID: number;
    HLIST: number[];
}

export interface Icountry {
    CID: number;
    CNAME: string;
}

export interface Istate {
    SID: number;
    SNAME: string;
    CID: number;
}

export interface Ihobby {
    HID: number;
    HNAME: string;
    STATUS: boolean;
}

Angularjs Services :

import { Injectable } from '@angular/core';
import { Idoctor, Icountry, Istate, Ihobby } from './doctor.model';
import { Http, Headers, Request, RequestMethod, Response, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';


@Injectable()
export class DoctorService {
    constructor(private _http: Http) { }
    Getc(): Promise<Icountry[]> {
        return this._http.get('http://localhost:3592/api/Doctorservices/Countries')
            .map((res: Response) => <Icountry[]>res.json())
            .toPromise();
    }
    Geth(): Promise<Ihobby[]> {
        return this._http.get('http://localhost:3592/api/Doctorservices/Hobbies')
            .map((res: Response) => <Ihobby[]>res.json())
            .toPromise();
    }
    Getd(): Promise<Idoctor[]> {
        return this._http.get('http://localhost:3592/api/Doctorservices/Doctors')
            .map((res: Response) => <Idoctor[]>res.json())
            .toPromise();
    }
    Get(did: number): Promise<Idoctor> {
        return this._http.get('http://localhost:3592/api/Doctorservices/Doctor/' + did)
            .map((res: Response) => <Idoctor>res.json())
            .toPromise();
    }
    Gets(cid: number): Promise<Istate[]> {
        return this._http.get('http://localhost:3592/api/Doctorservices/State/' + cid)
            .map((res: Response) => <Istate[]>res.json())
            .toPromise();
    }
    Save(doc: Idoctor): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Post, headers: headerOptions });
        return this._http.post('http://localhost:3592/api/Doctorservices/Save', JSON.stringify(doc), requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
    Update(doc: Idoctor): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
        return this._http.put('http://localhost:3592/api/Doctorservices/Update/' + doc.DID, JSON.stringify(doc), requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
    Delete(did: number): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Delete, headers: headerOptions });
        return this._http.delete('http://localhost:3592/api/Doctorservices/Delete/' + did, requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
}

Angularjs Component:

import { Component, OnInit } from '@angular/core';
import { Idoctor, Icountry, Istate, Ihobby } from '../doctors/doctor.model';
import { DoctorService } from './doctor.services';

@Component({
  selector: 'app-doctor-create',
  templateUrl: './doctor-create.component.html',
  styleUrls: ['./doctor-create.component.css']
})
export class DoctorCreateComponent implements OnInit {
  DOCTOR: Idoctor;
  listc: Icountry[];
  lists: Istate[];
  listh: Ihobby[];
  list: Idoctor[];

  constructor(private ds: DoctorService) { }

  ngOnInit() {
    this.reset();
    this.fill();
  }
  fx(cid: number): void {
    this.ds.Gets(cid).then(data => {
      if (data == null) {
        alert('Service return null value.');
      } else {
        this.lists = data;
      }
    });
  }
  fillddl(): void {
    this.fx(this.DOCTOR.CID);
  }
  reset(): void {
    this.DOCTOR = {
      DID: null,
      NAME: null,
      ADDRESS: null,
      PASSWORD: null,
      CPASSWORD: null,
      GENDER: null,
      ISMARRIED: true,
      CID: null,
      SID: null,
      HLIST: []
    };
    this.ds.Getc().then(data => {
      if (data == null) {
        alert('Service return null value.');
      } else {
        this.listc = data;
      }
    });
    this.ds.Geth().then(data => {
      if (data == null) {
        alert('Service return null value.');
      } else {
        this.listh = data;
      }
    });
  }
  fill(): void {
    this.ds.Getd().then(data => this.list = data);
  }
  edit(id: number): void {
    this.ds.Get(id).then(data => {
      this.fx(data.CID);
      this.DOCTOR = data;
    });
  }
  del(id: number): void {
    if (confirm('Do you want to delete it ?')) {
      this.ds.Delete(id).then(data => {
        alert(data);
        this.fill();
      });
    }

  }
  save(isValid: boolean): void {
    if (isValid === false) {
      this.ds.Save(this.DOCTOR).then(data => {
        alert(data);
        this.reset();
        this.fill();
      });
    }
  }
  update(isValid: boolean): void {
    if (isValid === false) {
      this.ds.Update(this.DOCTOR).then(data => {
        alert(data);
        this.reset();
        this.fill();
      });
    }
  }
}