Saturday, 16 June 2018

validation in angularjs 5 & web api 2

View Model :

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

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

        public STAPVM()
        {
            HLIST = new List<HOBBY>();
        }

    }
}

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/Stapservices")]
    public class StapservicesController : ApiController
    {
        [Route("Countries")]
        [HttpGet]
        public IHttpActionResult Countries()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.COUNTRies.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [Route("Hobbies")]
        [HttpGet]
        public IHttpActionResult Hobbies()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.HOBBies.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [Route("Staps")]
        [HttpGet]
        public IHttpActionResult Staps()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.STAPs.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [Route("STATE/{CID:int}")]
        [HttpGet]
        public IHttpActionResult STATE(int CID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.STATEs.Where(m=>m.CID==CID).ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [Route("Stap/{STID:int}",Name ="Stap")]
        [HttpGet]
        public IHttpActionResult Stap(int STID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    STAPVM vm = obj.STAPs.Select(e => new STAPVM { STID = e.STID, NAME = e.NAME, ADDRESS = e.ADDRESS, PASSWORD = e.PASSWORD, GENDER = e.GENDER, ISMARRIED = e.ISMARRIED, CID = e.CID, SID = e.SID }).SingleOrDefault(m => m.STID == STID);
                    var data = (
                        from x in obj.HMAPs.Where(e => e.STID == STID).ToList()
                        join y in obj.HOBBies on x.HID equals y.HID
                        select new HOBBY { HID = y.HID, HNAME = y.HNAME, STATUS = true }
                              ).ToList();
                    var data1 = obj.HOBBies.Select(e => new { e.HID, e.HNAME }).ToList().Except(data.Select(m => new { m.HID, m.HNAME })).ToList().Select(p => new HOBBY { HID = p.HID, HNAME = p.HNAME, STATUS = false }).ToList();
                    vm.HLIST = data.Union(data1).ToList();
                    return Ok(vm);
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [Route("Save")]
        [HttpPost]
        public IHttpActionResult Save(STAPVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    STAP st = new STAP();
                    st.STID = vm.STID;
                    st.NAME = vm.NAME;
                    st.ADDRESS = vm.ADDRESS;
                    st.PASSWORD = vm.PASSWORD;
                    st.GENDER = vm.GENDER;
                    st.ISMARRIED = vm.ISMARRIED;
                    st.CID = vm.CID;
                    st.SID = vm.SID;
                    obj.STAPs.Add(st);
                    obj.SaveChanges();
                    obj.HMAPs.AddRange(vm.HLIST.Where(m=>m.STATUS==true).Select(p => new HMAP { STID = vm.STID, HID = p.HID }));
                    obj.SaveChanges();
                    return Created(new Uri(Url.Link("Stap", new { STID = vm.STID })), "Data Saved.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [Route("Update/{STID:int}")]
        [HttpPut]
        public IHttpActionResult Update([FromUri]int STID,[FromBody]STAPVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    STAP st = obj.STAPs.Find(STID);
                    st.NAME = vm.NAME;
                    st.ADDRESS = vm.ADDRESS;
                    st.PASSWORD = vm.PASSWORD;
                    st.GENDER = vm.GENDER;
                    st.ISMARRIED = vm.ISMARRIED;
                    st.CID = vm.CID;
                    st.SID = vm.SID;
                    obj.SaveChanges();
                    obj.HMAPs.RemoveRange(obj.HMAPs.Where(e => e.STID == STID));
                    obj.SaveChanges();
                    obj.HMAPs.AddRange(vm.HLIST.Where(m=>m.STATUS==true).Select(p => new HMAP { STID = vm.STID, HID = p.HID }));
                    obj.SaveChanges();
                    return Ok("Data Updated.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [Route("Delete/{STID:int}")]
        [HttpDelete]
        public IHttpActionResult Delete([FromUri]int STID, [FromBody]STAPVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    STAP st = obj.STAPs.Find(STID);
                    obj.STAPs.Remove(st);
                    obj.SaveChanges();
                    obj.HMAPs.RemoveRange(obj.HMAPs.Where(e => e.STID == STID));
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}


Angular Model


export interface Istap {
    STID: number;
    NAME: string;
    ADDRESS: string;
    PASSWORD: string;
    GENDER: string;
    ISMARRIED: boolean;
    CID: number;
    SID: number;
    HLIST: Ihobby[];
}

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;
}

Angular Service :

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestMethod, RequestOptions } from '@angular/http';
import { Istap, Icountry, Istate, Ihobby } from '../create-stap/stap.model';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()

export class StapServices {

    constructor(private _hppt: Http) { }
    Getc(): Observable<Icountry[]> {
        return this._hppt.get('http://localhost:3592/api/Stapservices/Countries')
            .map((response: Response) => <Icountry[]>response.json());
    }
    Geth(): Observable<Ihobby[]> {
        return this._hppt.get('http://localhost:3592/api/Stapservices/Hobbies')
            .map((response: Response) => <Ihobby[]>response.json());
    }
    Gets(cid: number): Observable<Istate[]> {
        return this._hppt.get('http://localhost:3592/api/Stapservices/STATE/' + cid)
            .map((response: Response) => <Istate[]>response.json());
    }
    Gete(): Observable<Istap[]> {
        return this._hppt.get('http://localhost:3592/api/Stapservices/Staps')
            .map((response: Response) => <Istap[]>response.json());
    }
    Get(stid: number): Observable<Istap> {
        return this._hppt.get('http://localhost:3592/api/Stapservices/Stap/' + stid)
            .map((response: Response) => <Istap>response.json());
    }
    Save(STAP: Istap): any {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Post, headers: headerOptions });
        return this._hppt.post('http://localhost:3592/api/Stapservices/Save', JSON.stringify(STAP), requestOptions)
            .map((res: Response) => <any>res.json());
    }
    Update(STAP: Istap): any {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
        return this._hppt.put('http://localhost:3592/api/Stapservices/Update/' + STAP.STID, JSON.stringify(STAP), requestOptions)
            .map((res: Response) => <any>res.json());
    }
    Delete(stid: number): any {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Delete, headers: headerOptions });
        return this._hppt.delete('http://localhost:3592/api/Stapservices/Delete/' + stid, requestOptions)
            .map((res: Response) => <any>res.json());
    }
}

Angular  component :

import { Component, OnInit } from '@angular/core';
import { Istap, Icountry, Istate, Ihobby } from '../create-stap/stap.model';
import { StapServices } from '../create-stap/stap.services';

@Component({
  selector: 'app-create-stap',
  templateUrl: './create-stap.component.html',
  styleUrls: ['./create-stap.component.css']
})
export class CreateStapComponent implements OnInit {
  STAP: Istap;
  listc: Icountry[];
  lists: Istate[];
  listh: Ihobby[];
  list: Istap[];
  message: string;
  mark: number;
  errMessage: string;
  constructor(private stapservice: StapServices) {
    this.reset();
    this.stapservice.Getc().subscribe(data => this.listc = data);
    this.fill();
  }

  ngOnInit() {
  }
  fill(): void {
    this.stapservice.Gete().subscribe(res => this.list = res);
  }
  reset(): void {
    this.STAP = {
      STID: null,
      NAME: null,
      ADDRESS: null,
      PASSWORD: null,
      GENDER: null,
      ISMARRIED: true,
      CID: null,
      SID: null,
      HLIST: []
    };
    this.stapservice.Geth().subscribe(data => this.STAP.HLIST = data);
  }
  fx(CID: number): void {
    this.stapservice.Gets(CID).subscribe(data => this.lists = data);
  }
  fillddl(): void {
    this.fx(this.STAP.CID);
  }
  save(isValid: boolean): void {
    if (!isValid) {
      this.stapservice.Save(this.STAP).subscribe(res => this.message = res.data);
      alert(this.message);
      this.reset();
      this.fill();
    }

  }
  edit(id: number): void {
    this.stapservice.Get(id).subscribe(res => this.STAP = res);
    this.fx(this.STAP.CID);
  }
  del(id: number): void {
    if (confirm('Do you want to delete it ?')) {
      this.stapservice.Delete(id).subscribe(res => this.message = res.data);
      alert(this.message);
      this.fill();
    }
  }

  update(isValid: boolean): void {
    if (!isValid) {
      this.stapservice.Update(this.STAP).subscribe(res => this.message = res.data);
      alert(this.message);
      this.reset();
      this.fill();
    }

  }
  cvalidation(): void {
    this.mark = 0;
    this.STAP.HLIST.forEach(element => {
      if (element.STATUS === true) {
        this.mark = 1;
      }
    });
    if (this.mark === 0) { this.errMessage = 'Please select a hobby.'; } else { this.errMessage = ''; }
  }
}


Angular View :


<form class="form-horizontal" #stapForm="ngForm"  >
  <div class="form-group " [class.has-error]="STID.invalid && STID.touched" [class.has-success]="STID.valid">
      <label class="control-label col-lg-4">STID</label>
      <div class="col-lg-4">
          <input type="text"  name="STID" class="form-control" [(ngModel)]="STAP.STID" #STID="ngModel" required />
      </div>
      <span class="help-block" *ngIf="STID.invalid && STID.touched">
          STID 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" name="NAME" [(ngModel)]="STAP.NAME" #NAME="ngModel" required />
    </div>
    <span class="help-block" *ngIf="NAME.invalid && NAME.touched">
        Name should not blank.
    </span>
</div>
<div class="form-group" [class.has-success]="ADDRESS.valid" [class.has-error]="ADDRESS.invalid && ADDRESS.touched">
    <label class="control-label col-lg-4">ADDRESS</label>
    <div class="col-lg-4">
        <textarea class="form-control" name="ADDRESS" [(ngModel)]="STAP.ADDRESS" #ADDRESS="ngModel" required ></textarea>
    </div>
    <span class="help-block" *ngIf="ADDRESS.invalid && ADDRESS.touched">
        Address should not blank.
    </span>
</div>
<div class="form-group" >
    <label class="control-label col-lg-4">HOBBY</label>
    <div class="col-lg-4">
       <div class="form-control"  style="height:110px; list-style-type: none;" >
           <li *ngFor="let c of STAP.HLIST">
            <input type="checkbox" name={{c.HID}} #HLIST="ngModel"  value={{c.HID}} [(ngModel)]=c.STATUS/>{{c.HNAME}}
           </li>
       </div>
    </div>
   <span style="color:red">{{errMessage}}</span>
</div>
<div class="form-group" [class.has-success]="PASSWORD.valid" [class.has-error]="PASSWORD.invalid && PASSWORD.touched">
    <label class="control-label col-lg-4">PASSWORD</label>
    <div class="col-lg-4">
        <input (keyup)="cvalidation()"  type="password" class="form-control" name="PASSWORD" [(ngModel)]="STAP.PASSWORD" #PASSWORD="ngModel" required >
    </div>
    <span class="help-block" *ngIf="PASSWORD.invalid && PASSWORD.touched">
        Password should not blank.
    </span>
</div>
<div class="form-group" [class.has-success]="GENDER.valid" [class.has-error]="GENDER.invalid && GENDER.touched">
    <label class="control-label col-lg-4">GENDER</label>
    <div class="col-lg-4">
        <input  type="radio" value="Male"  name="GENDER" [(ngModel)]="STAP.GENDER" #GENDER="ngModel" required >Male
        <input  type="radio" value="Female"  name="GENDER" [(ngModel)]="STAP.GENDER" #GENDER="ngModel" required >Female
    </div>
    <span class="help-block" *ngIf="GENDER.invalid && GENDER.touched">
        Please select a gender.
    </span>
</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)]="STAP.ISMARRIED" #ISMARRIED="ngModel">
     
    </div>
 
</div>

<div class="form-group" [class.has-success]="CID.valid" [class.has-error]="CID.invalid && CID.touched">
    <label class="control-label col-lg-4">COUNTRY</label>
    <div class="col-lg-4">
       <select class="form-control" required name="CID" (change)="fillddl()" [(ngModel)]="STAP.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" *ngIf="CID.invalid && CID.touched">
        Please select a country.
    </span>
</div>
<div class="form-group" [class.has-success]="SID.valid" [class.has-error]="SID.invalid && SID.touched">
    <label class="control-label col-lg-4">STATE</label>
    <div class="col-lg-4">
       <select class="form-control" required name="SID" [(ngModel)]="STAP.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" *ngIf="SID.invalid && SID.touched">
        Please select a state.
    </span>
</div>

<div class="form-group">
    <label class="control-label col-lg-4"></label>
    <div class="col-lg-4">
        <input type="button"  style="width:80px" class="btn btn-primary" value="Save" (click)="save(stapForm.invalid)" />
        <input type="button" style="width:80px" class="btn btn-primary" value="Update" (click)="update(stapForm.invalid)" />
        <input type="button" style="width:80px" class="btn btn-primary" value="Reset" (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>EID</th>
                    <th>NAME</th>
                    <th>ACTION</th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let c of list">
                    <td>{{c.STID}}</td>
                    <td>{{c.NAME}}</td>
                    <td>
                        <a (click)="edit(c.STID)">Edit</a> |
                        <a (click)="del(c.STID)">Delete</a>
                    </td>
                </tr>
            </tbody>

        </table>
    </div>
</div>

</form>

No comments:

Post a Comment