Sunday 16 December 2018

CURD operation using reactive forms with validation in angularjs6


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/Cstservices")]
    public class CstservicesController : ApiController
    {
        [HttpGet]
        [Route("Countries")]
        public HttpResponseMessage Countries()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.COUNTRies.ToList());
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest,ex);
            }
        }
        [HttpGet]
        [Route("Csts")]
        public HttpResponseMessage Csts()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.CSTs.ToList());
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpGet]
        [Route("Cst/{MID:int}",Name ="Cst")]
        public HttpResponseMessage Cst(int MID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.CSTs.Find(MID));
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpGet]
        [Route("State/{CID:int}")]
        public HttpResponseMessage State(int CID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.STATEs.Where(p=>p.CID==CID).ToList());
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpPost]
        [Route("Save")]
        public HttpResponseMessage Save(CST vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(vm).State = EntityState.Added;
                    obj.SaveChanges();
                    var req = Request.CreateResponse(HttpStatusCode.Created,"Data Saved.");
                    req.Headers.Location = new Uri(Url.Link("Cst", new { MID = vm.MID }));
                    return req;
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpPut]
        [Route("Update/{MID:int}")]
        public HttpResponseMessage Update([FromUri]int MID,[FromBody]CST vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(vm).State = EntityState.Modified;
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Updated.");
                 
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpDelete]
        [Route("Delete/{MID:int}")]
        public HttpResponseMessage Delete([FromUri]int MID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(obj.CSTs.Find(MID)).State = EntityState.Deleted;
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Deleted.");

                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
    }
}
ANGULAR MODELS :
export interface Icst {
    MID: number;
    NAME: string;
    PASSWORD: string;
    ADDRESS: string;
    EMAIL: string;
    GENDER: string;
    CID: number;
    SID: number;
}
export interface Icountry {
    CID: number;
    CNAME: string;
}
export interface Istate {
    SID: number;
    SNAME: string;
    CID: number;
}

ANGULAR COMPONENT :

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Icst, Icountry, Istate } from './cst.model';
import { CstServices } from './cst.services';

@Component({
  selector: 'app-createcst',
  templateUrl: './createcst.component.html',
  styleUrls: ['./createcst.component.css']
})
export class CreatecstComponent implements OnInit {
  cstForm: FormGroup;
  CST: Icst;
  list: Icst[];
  listc: Icountry[];
  lists: Istate[];

  constructor(private fb: FormBuilder, private cs: CstServices) { }

  ngOnInit() {
    this.cstForm = this.fb.group({
      MID: [null, Validators.required],
      NAME: [null, Validators.required],
      PASSWORD: [null, [Validators.required, Validators.minLength(6), Validators.maxLength(8)]],
      ADDRESS: [null, Validators.required],
      EMAIL: [null, [Validators.required, Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')]],
      GENDER: [null, Validators.required],
      CID: [null, Validators.required],
      SID: [null, Validators.required]
    });
    this.cs.Getc().then(data => this.listc = data);
    this.CLR();
    this.fill();
    this.cstForm.get('CID').valueChanges.subscribe((value: number) => {
      this.fx(value);
    });
  }
  CLR(): void {
    this.CST = {
      MID: null,
      NAME: null,
      PASSWORD: null,
      ADDRESS: null,
      GENDER: null,
      EMAIL: null,
      CID: null,
      SID: null
    };
    this.cstForm.reset();
  }
  fx(cid: number): void {
    this.cs.Gets(cid).then(data => this.lists = data);
  }
  fill(): void {
    this.cs.Getm().then(data => this.list = data );
  }
  del(mid: number): void {
    if (confirm('Do you want to delete it ?')) {
      this.cs.Delete(mid).then(data => {
        alert(data);
        this.fill();
      });
    }
  }
  edit(mid: number): void {
    this.cs.Get(mid).then(data => {
    this.cstForm.setValue({
       MID: data.MID,
       NAME: data.NAME,
       PASSWORD: data.PASSWORD,
       ADDRESS: data.ADDRESS,
       GENDER: data.GENDER,
       EMAIL: data.EMAIL,
       CID: data.CID,
       SID: data.SID
     });
     this.fx(data.CID);
    });
  }
  save(): void {
    this.CST.MID = this.cstForm.get('MID').value;
    this.CST.NAME = this.cstForm.get('NAME').value;
    this.CST.PASSWORD = this.cstForm.get('PASSWORD').value;
    this.CST.ADDRESS = this.cstForm.get('ADDRESS').value;
    this.CST.GENDER = this.cstForm.get('GENDER').value;
    this.CST.EMAIL = this.cstForm.get('EMAIL').value;
    this.CST.CID = this.cstForm.get('CID').value;
    this.CST.SID = this.cstForm.get('SID').value;
    this.cs.Save(this.CST).then(data => {
    alert(data);
    this.CLR();
    this.fill();
    });
  }
  update(): void {
    this.CST.MID = this.cstForm.get('MID').value;
    this.CST.NAME = this.cstForm.get('NAME').value;
    this.CST.PASSWORD = this.cstForm.get('PASSWORD').value;
    this.CST.ADDRESS = this.cstForm.get('ADDRESS').value;
    this.CST.GENDER = this.cstForm.get('GENDER').value;
    this.CST.EMAIL = this.cstForm.get('EMAIL').value;
    this.CST.CID = this.cstForm.get('CID').value;
    this.CST.SID = this.cstForm.get('SID').value;
    this.cs.Update(this.CST).then(data => {
    alert(data);
    this.CLR();
    this.fill();
    });
  }
  reset(): void {
    this.cstForm.reset();
  }
}

ANGULAR SERVICE :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Icst, Icountry, Istate } from './cst.model';
import 'rxjs/add/operator/toPromise';


@Injectable()
export class CstServices {
    baseUrl = 'http://localhost:2813/api/Cstservices';
    constructor(private _http: HttpClient) {
    }
    Getc(): Promise<Icountry[]> {
        return this._http.get<Icountry[]>(`${this.baseUrl}/${'Countries'}`)
            .toPromise();
    }
    Gets(cid: number): Promise<Istate[]> {
        return this._http.get<Istate[]>(`${this.baseUrl}/${'State'}/${cid}`)
            .toPromise();
    }
    Getm(): Promise<Icst[]> {
        return this._http.get<Icst[]>(`${this.baseUrl}/${'Csts'}`)
            .toPromise();
    }
    Get(mid: number): Promise<Icst> {
        return this._http.get<Icst>(`${this.baseUrl}/${'Cst'}/${mid}`)
            .toPromise();
    }
    Save(icst: Icst): Promise<string> {
        return this._http.post<string>(`${this.baseUrl}/${'Save'}`
            , JSON.stringify(icst)
            , { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }
        )
            .toPromise();
    }
    Update(icst: Icst): Promise<string> {
        return this._http.put<string>(`${this.baseUrl}/${'Update'}/${icst.MID}`
            , JSON.stringify(icst)
            , { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }
        )
            .toPromise();
    }
    Delete(mid: number): Promise<string> {
        return this._http.delete<string>(`${this.baseUrl}/${'Delete'}/${mid}`
            , { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }
        )
            .toPromise();
    }
}

ANGULAR VIEW :

<form class="form-horizontal" [formGroup]="cstForm">
    <div class="form-group " [ngClass]="{'has-error':cstForm.get('MID').errors && (cstForm.get('MID').touched || cstForm.get('MID').dirty) }">
        <label class="control-label col-lg-4">MID</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" id="MID" formControlName="MID" />
        </div>
        <span *ngIf="cstForm.get('MID').errors && (cstForm.get('MID').touched || cstForm.get('MID').dirty)" class="help-block">Mid should be not blank.</span>
    </div>

    <div class="form-group " [ngClass]="{'has-error':cstForm.get('NAME').errors && (cstForm.get('NAME').touched || cstForm.get('NAME').dirty) }">
        <label class="control-label col-lg-4">NAME</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" id="NAME" formControlName="NAME" />
        </div>
        <span *ngIf="cstForm.get('NAME').errors && (cstForm.get('NAME').touched || cstForm.get('NAME').dirty)" class="help-block">Name should be not blank.</span>
    </div>

    <div class="form-group " [ngClass]="{'has-error':cstForm.get('PASSWORD').errors && (cstForm.get('PASSWORD').touched || cstForm.get('PASSWORD').dirty) }">
        <label class="control-label col-lg-4">PASSWORD</label>
        <div class="col-lg-4">
            <input type="password"  class="form-control" id="PASSWORD" formControlName="PASSWORD" />
        </div>
        <span class="help-block" *ngIf="cstForm.get('PASSWORD').errors && (cstForm.get('PASSWORD').touched || cstForm.get('PASSWORD').dirty)">
        <span  *ngIf="cstForm.get('PASSWORD').errors.required">Password should be not blank.</span>
        <span *ngIf="cstForm.get('PASSWORD').errors.minlength">Password min length is 6.</span>
        <span *ngIf="cstForm.get('PASSWORD').errors.maxlength">Password max length is 8.</span>
       </span>
    </div>
    <div class="form-group " [ngClass]="{'has-error':cstForm.get('ADDRESS').errors && (cstForm.get('ADDRESS').touched || cstForm.get('ADDRESS').dirty) }">
        <label class="control-label col-lg-4">ADDRESS</label>
        <div class="col-lg-4">
            <textarea class="form-control" id="ADDRESS" formControlName="ADDRESS" ></textarea>
        </div>
        <span *ngIf="cstForm.get('ADDRESS').errors && (cstForm.get('ADDRESS').touched || cstForm.get('ADDRESS').dirty)" class="help-block">Address should be not blank.</span>
    </div>
    <div class="form-group " [ngClass]="{'has-error':cstForm.get('EMAIL').errors && (cstForm.get('EMAIL').touched || cstForm.get('EMAIL').dirty) }">
        <label class="control-label col-lg-4">EMAIL</label>
        <div class="col-lg-4">
            <input type="text"  class="form-control" id="EMAIL" formControlName="EMAIL" />
        </div>
        <span *ngIf="cstForm.get('EMAIL').errors && (cstForm.get('EMAIL').touched || cstForm.get('EMAIL').dirty)" class="help-block">
        <span *ngIf="cstForm.get('EMAIL').errors.required">Password should be not blank.</span>
        <span *ngIf="cstForm.get('EMAIL').errors.pattern">Invalid email id.</span>
    </span>
    </div>
    <div class="form-group " [ngClass]="{'has-error':cstForm.get('GENDER').errors && (cstForm.get('GENDER').touched || cstForm.get('GENDER').dirty) }">
        <label class="control-label col-lg-4">GENDER</label>
        <div class="col-lg-4">
            <input type="radio" id="GENDER" formControlName="GENDER" value="Male" />Male
            <input type="radio" id="GENDER" formControlName="GENDER" value="Female" />Female
        </div>
        <span *ngIf="cstForm.get('GENDER').errors && (cstForm.get('GENDER').touched || cstForm.get('GENDER').dirty)" class="help-block">Please select a gender.</span>
    </div>

    <div class="form-group " [ngClass]="{'has-error':cstForm.get('CID').errors && (cstForm.get('CID').touched || cstForm.get('CID').dirty) }">
        <label class="control-label col-lg-4">COUNTRY</label>
        <div class="col-lg-4">
            <select id="CID" formControlName="CID" class="form-control">
                <option [ngValue]="null" class="form-control">Select</option>
                <option *ngFor="let c of listc" [value]="c.CID">{{c.CNAME}}</option>
            </select>
        </div>
        <span *ngIf="cstForm.get('CID').errors && (cstForm.get('CID').touched || cstForm.get('CID').dirty)" class="help-block">Please select a country.</span>
    </div>

    <div class="form-group " [ngClass]="{'has-error':cstForm.get('SID').errors && (cstForm.get('SID').touched || cstForm.get('SID').dirty) }">
        <label class="control-label col-lg-4">STATE</label>
        <div class="col-lg-4">
            <select id="SID" formControlName="SID" class="form-control">
                <option [ngValue]="null" class="form-control">Select</option>
                <option *ngFor="let c of lists" [value]="c.SID">{{c.SNAME}}</option>
            </select>
        </div>
        <span *ngIf="cstForm.get('SID').errors && (cstForm.get('SID').touched || cstForm.get('SID').dirty)" class="help-block">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()" />
            <input type="button" style="width:80px" class="btn btn-primary" value="Update" (click)="update()" />
            <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>Sl No.</th>
                       <th>Name</th>
                       <th>Action</th>
                   </tr>
               </thead>
               <tbody>
                   <tr *ngFor="let c of list;let i=index">
                       <td>{{i+1}}</td>
                       <td>{{c.NAME}}</td>
                       <td>
                           <a (click)="edit(c.MID)">Edit</a> |
                           <a (click)="del(c.MID)">Delete</a>
                       </td>
                   </tr>
               </tbody>
           </table>
        </div>
    </div>






</form>

No comments:

Post a Comment